【发布时间】:2021-12-14 12:19:07
【问题描述】:
我想制作从左上角开始的蛇形矩阵, 没有字符串。 我不知道该怎么做,我需要帮助。 Snake matrix
【问题讨论】:
-
有没有什么方法可以不带字符串调用函数?
我想制作从左上角开始的蛇形矩阵, 没有字符串。 我不知道该怎么做,我需要帮助。 Snake matrix
【问题讨论】:
java中的这个方法会生成蛇形矩阵n * m
public static int[][] snakeMatrix(int n, int m) {
int counter = 1;
int c = 0;
boolean isIncrease = true;
int[][] matrix = new int[n][m];
for (int i = m - 1; i >= 0; i--) {
for(int x = 0 ; x < n ; x++) {
matrix[c][i] = counter++;
if (isIncrease) c++;
else c--;
}
isIncrease = !isIncrease;
if (isIncrease) c = 0;
else c = n - 1;
}
return matrix;
}
在您的示例中,代码将是这样的
public static void main(String[] args) {
int[][] matrix = snakeMatrix(7, 4);
for (int[] array : matrix) {
System.out.println(Arrays.toString(array));
}
}
输出
[28, 15, 14, 1]
[27, 16, 13, 2]
[26, 17, 12, 3]
[25, 18, 11, 4]
[24, 19, 10, 5]
[23, 20, 9, 6]
[22, 21, 8, 7]
【讨论】: