循环通过网格

Pau*_*ock 4 java loops

我使用这两个简单的循环从高到低,从右到左搜索网格.

for(int y=0; y<height; y++){
  for(int x=width; x>=0; x--){
  }
}
Run Code Online (Sandbox Code Playgroud)

基本上,我想横向搜索网格,如下图所示,直到它覆盖所有单元格.我的方法效果不好,所以我在这里寻求帮助.

在此输入图像描述

我怎样才能以最快的方式实现这一目标?我相信这应该可以只使用两个循环,但我无法弄明白.

NPE*_*NPE 9

以下将这样做:

 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);
     }
 }
Run Code Online (Sandbox Code Playgroud)

这里h是高度,w是网格的宽度.

该算法基于以下观察:对于每个对角线,到顶部边缘和右边缘的距离的总和保持不变.

外环迭代对角线; 内环,对角线上的所有细胞.