I use these two simple loops to search through a grid from height to bottom, right to left.
for(int y=0; y<height; y++){
for(int x=width; x>=0; x--){
}
}
Basically, I want to search through the grid sideways like the numbers in the picture below until it covers all the cells. My approach hasn't worked out well so I'm asking for help here.
How can I accomplish this the quickest way possible? I believe this should be possible to do using just two loops but I can't figure it out.
The following will do it:
final int h = 4;
final int w = 3;
for (int d = 0; d < w + h; d++) {
for (int y = 0; y < h; y++) {
int x = w - d + y;
if (x < 0 || x >= w) continue;
System.out.printf("%d %d\n", x, y);
}
}
Here, h
is the height and w
is the width of the grid.
The algorithm is based on the observation that for each diagonal, the sum of the distances to the top edge and to the right edge remains constant.
The outer loop iterates over the diagonals; the inner loop, over all cells on the diagonal.
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