从下角遍历一个二维数组矩阵左右上角 [英] Traversing a 2D array matrix diagonally from bottom left to upper right
本文介绍了从下角遍历一个二维数组矩阵左右上角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个二维数组psented一个3×4矩阵重新$ P $:
I have a 3x4 matrix represented by a 2D array:
. 0 1 2 3
0 a c f i
1 b e h k
2 d g j l
和我的方法遍历角切片是对待每片称为总和,是这样的:
and my approach to traverse the diagonal slice was to treat each slice as a sum, like this:
a = (0+0) = 0
b,c = (0+1),(1+0) = 1
d,e,f = (0+2),(1+1),(2+0) = 2
g,h,i = (1+2),(2+1),(3+0) = 3
j, k = (2+2),(3+1) = 4
l = (3+2) = 5
不过,我的code现在打印它,我希望它相反的方向,这是自到左下右上。
However, my code right now prints it in the opposite way that I want it to, which is from upper right to bottom left.
电流输出是:
acbfedihgkjl
所需的输出是:
abcdefghijkl
for (int sum = 0; sum <= numRows + numColumns - 2; sum++) {
for (int i = 0; i < numRows; i++) {
int j = sum - i;
if ((i >= 0 && i < numRows) && (j >= 0 && j < numColumns)) {
System.out.print(array[i][j]);
}
}
}
有人能指出我如何解决我的code来获得我想要的输出?正确的方向
Can somebody point me in the right direction on how to fix my code to get the output that I want?
推荐答案
虽然不是很pretty,我认为这将做到这一点:
While it isn't very pretty, I think this will do it:
int i = 0;
int j = 0;
while (true) {
System.out.println("" + array[i][j]);
--i;
++j;
if (i < 0) {
if (j == numCols)
break;
i = Math.min(j, numRows - 1);
j = Math.max(j - numCols + 2, 0);
} else if (j >= numCols) {
if (i == numRows - 2)
break;
i = numRows - 1;
j = Math.max(j + 2 - numCols + i, 0);
}
}
这篇关于从下角遍历一个二维数组矩阵左右上角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文