I am new to competitive programming, and I noticed frequently, many of the great coders have these four lines in their code (particularly in those involving arrays):
int di[] = { 1, -1, 0, 0, 1, -1, 1, -1 }; int dj[] = { 0, 0, 1, -1, 1, -1, -1, 1 }; int diK[] = { -2, -2, -1, 1, 2, 2, 1, -1 }; int djK[] = { -1, 1, 2, 2, 1, -1, -2, -2 };
What does this really signify and what is technique used for?
This is a technique to encode all directions as arrays - every pair of di[i],dj[i]
is a different direction.
If we imagine we have a piece at a location x,y, and we want to add onto its x and its y value to move it to a nearby location, 1,0 is east, -1,0 is west, 0,1 is south, 0,-1 is north and so on.
(Here I have said top left is 0,0 and bottom right is 4,4 and shown what move each index of the arrays will make from the central point, X, at 2,2.)
..... .536. .1X0. .724. .....
The way it is set up, if you do ^1
(^
being bitwise XOR) on the index you get the opposite direction - 0 and 1 are opposites, 2 and 3 are opposites and so on. (Another way to set it up is to go clockwise starting at north - then ^4
gets you the opposite direction.)
Now you can test all directions from a given point by looping over your di
and dj
arrays, instead of needing to write out each direction on its own line (for eight in total!) (Just don't forget to do bounds checking :) )
diK
and djK
form all knights directions instead of all adjacent directions. Here, ^1
will flip along one axis, ^4
will give the opposite knight leap.
.7.6. 0...5 ..K.. 1...4 .2.3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With