想象一个菱形的等距地图,它基本上是一个二维数组,有(x,y)坐标,顶部单元格作为原点,在单元格中标记:
我想按照以下顺序从后到前迭代这些单元格:
通过未知的同侧地图以这种方式循环的算法是什么?
预期输出:[0,0],[0,1],[1,0],[0,2],[1,1],[2,0],[0,3]等< / p>
答案 0 :(得分:3)
python 伪代码:
def iterate_cells(n):
for i in range(n):
for j in range(i+1):
yield (j, i-j)
for i in range(1, n+1):
for j in range(n - i):
yield(i+j, n-j-1)
输出:
In [119]: list(iterate_cells(5))
Out[119]:
[(0, 0),
(0, 1),
(1, 0),
(0, 2),
(1, 1),
(2, 0),
(0, 3),
(1, 2),
(2, 1),
(3, 0),
(0, 4),
(1, 3),
(2, 2),
(3, 1),
(4, 0),
(1, 4),
(2, 3),
(3, 2),
(4, 1),
(2, 4),
(3, 3),
(4, 2),
(3, 4),
(4, 3),
(4, 4)]
答案 1 :(得分:0)
考虑到地图包含在矩阵M(n,n)中:
// lateral loop above diagonal
for (int i=0; i<n; i++) {
// diagonal loop
for (int j=0; j<i; j++) {
// the coords you are looking for are: row=(i-j), col=(i+j)
int currentTileValue = M[i-j, i+j];
}
}
// sub-diagonal lateral loop
for (int j=1; j<n; j++) {
// diagonal loop
for (int i=0; i<(n-j); i++) {
// the coords you are looking for are: row=(j-i), col=(j+i)
int currentTileValue = M[j-i, j+i];
}
}
没有详细测试,但我认为我认为它有效。无论如何你都明白了。