JAVA:如何创建一个蛇形矩阵 [英] JAVA : How to create a snake shape matrix
问题描述
您好我想创建使用二维数组在控制台上的矩阵。这个想法是,输出应该像这样的:
Hi I am trying to create a matrix on the console using 2D array. The idea is that the output should look like this one :
1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13
有没有谁拥有一个想法,它是如何做到的呢?
Is there any one who has an idea how it can be done?
推荐答案
很少有东西您可以从矩阵猜测: -
Few things you can guess from the matrix: -
-
首先,你必须先移动到下一列前遍历列的所有行
First, you have to traverse all rows of a columns first before moving to the next column
其次,你需要向下
和向上
的方向每次迭代
Second, you need to alternate between downwards
and upwards
direction on each iteration
所以,你需要的两个嵌套的循环,通过迭代行的特定列。一会从 0一行去到最大 - 1
,接下来会从行=最大值 - 1 0
So, you would need two nested for loop, for iterating through rows for a particular column. One will go from row 0 to max - 1
, and the next will go from row = max - 1 to 0
.
现在,交替迭代的方向,你可以使用一个布尔变量,而内循环完成的每一次迭代后,其切换。
Now, to alternate the iteration direction, you can use a boolean variable, and toggle it after each iteration of inner loop finishes.
每个回路需要内部的的if-else
来包围。两者将在一定的条件下被执行。如果布尔向下= FALSE;
,然后循环向上移动将被执行,反之亦然
Each loop needs to be enclosed inside an if-else
. Both of them will be executed on a certain condition. If boolean downwards = false;
, then loop moving upwards will be executed and vice-versa.
在每次迭代中,填补了当前单元格与整数计数器,你将不得不使用 1
来初始化,并且每个填充后增加它。
On each iteration, fill the current cell with an integer counter, that you would have to initialize with 1
, and increment it after each fill.
伪code: -
// 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
}
这篇关于JAVA:如何创建一个蛇形矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!