遍历网格 [英] Looping through a grid

查看:63
本文介绍了遍历网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

以下将完成此操作:

 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);
     }
 }

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

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.

这篇关于遍历网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆