Looping through a grid

时光毁灭记忆、已成空白 提交于 2021-01-27 05:46:26

问题


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.

enter image description 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.


回答1:


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.



来源:https://stackoverflow.com/questions/10394931/looping-through-a-grid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!