嗨我想在控制台上使用二维数组创建一个矩阵。我们的想法是,输出应该是这样的一个:JAVA:如何创建一个蛇形状矩阵
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
有没有谁拥有一个想法,它是如何做到的任何一个?
嗨我想在控制台上使用二维数组创建一个矩阵。我们的想法是,输出应该是这样的一个:JAVA:如何创建一个蛇形状矩阵
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
有没有谁拥有一个想法,它是如何做到的任何一个?
很少有东西可以从矩阵猜测: -
首先,你必须先移动到下一列
二之前遍历列的所有行,则需要在每次迭代中在downwards
和upwards
之间交替
因此,您需要两个嵌套循环,用于遍历特定列的行。其中一个将从row 0 to max - 1
开始,而下一个将从row = max - 1 to 0
开始。
现在,要交替迭代方向,可以使用布尔变量,并在内循环每次迭代完成后切换它。
每个循环都需要包含在if-else
的内部。他们两人将在一定条件下执行。如果boolean downwards = false;
,则循环向上移动将被执行,反之亦然。
在每次迭代时,用整数计数器填充当前单元格,您必须用1
进行初始化,并在每次填充后对其进行增加。
伪代码: -
// Initialize variables row, col, and count = 1
boolean goDown = true;
int[][] matrix = new int[row][col]; // declare matrix
for i = 0 to col:
if (goDown)
for j = 0 to row: // Move in downwards direction
assign count++ to matrix[j][i]
// assign to `[j][i]` because, we have to assign to rows first
goDown = false; // Toggle goDown
else
for j = row - 1 to 0: // Move in upwards direction
assign count++ to matrix[j][i]
goDown = true; // toggle goDown
}
只是一些伪代码,希望它有帮助,并给你一些开始。
boolean goUp = false;
boolean goDown = true;
size = 4;
matrix[size][size];
k = 0;
l =0;
loop i->0 i < size*size i++
matrix[l][k] = i;
if(l==size and goDown)
goDown = false;
goUp = true;
k++;
else if(l==0 and goUp)
goDown = true;
goUp = false;
k++;
else
l = l+ (1*goDown?1:-1);
end loop;
。
int a = 4;
int b = 4;
int c = 1;
boolean direction = true;
int[][] arrey = new int[a][b];
for (int y = 0; y <= b - 1; y++) {
if (direction) {
for (int x = 0; x <= a - 1; x++) {
arrey[x][y] = c;
c++;
}
direction = false;
} else {
for (int x = a - 1; x >= 0; x--) {
arrey[x][y] = c;
c++;
}
direction = true;
}
}
for (int x = 0; x <= a - 1; x++) {
for (int y = 0; y <= b - 1; y++) {
System.out.print("["+arrey[x][y]+"]");
}
System.out.println("");
}
很好,您成功地将我的伪代码转换为真正的代码。 :) –
但理想情况下,您应该接受帮助您获得此解决方案的答案。但是,这也是你的选择。你总是可以回答自己的问题并接受它。 –
因为接受帮助你的答案是感谢这篇文章。我只是告诉你这个只是为了你的好处。并不是说我会为此做出代表。但是,假设你继续这样做,在某个时候,你将停止对你的回答收到良好的回应。 –
标签是作为功课,不要指望人们为你解决它。你有什么尝试? – user219882
您最后需要2个for-loops。你有什么尝试? – Mirco
我想,它可以通过一个'for'循环和几个'if'语句来解决 – svz