【发布时间】:2019-10-10 22:12:25
【问题描述】:
我必须创建一个矩阵 (N*M),其中每个单元格都根据特定遍历的顺序进行标记。
问题是我只为 (NN) 工作。我一直在寻找解决方案,因此它也适用于 (NM)。
例如 N*M 示例:
1 2 5 10
4 3 6 11
9 8 7 12
N*N 示例:
1 2 5 10
4 3 6 11
9 8 7 12
16 15 14 13
2x4 看起来像:
1 2 5 7
4 3 6 8
4x2 看起来像:
1 2
4 3
5 6
7 8
代码
public static int matrix[][];
public static void main(String[] args) {
borderLayout(5);
print();
}
public static void borderLayout(int size) {
matrix = new int[size][size];
for(int i = 0 ; i < size ; i ++) {
fillBorder(i);
}
}
public static void fillBorder(int n) {
int number = n*n+1;
int row = n;
int column = 0;
for(column = 0; column<=n; column++) {
System.out.println("COLUMN DRAWING");
matrix[row][column]=number++;
}
column--;
for(row = n; row>0 ; row--){
System.out.println("ROW DRAWING");
matrix[row-1][column] = number++;
}
print();
System.out.println("");
}
private static void print() {
int x = matrix.length;
int y = matrix[0].length;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(matrix[j][i]);
System.out.print(" ");
if (matrix[j][i] < 10) {
System.out.print(" ");
}
}
System.out.println();
}
}
【问题讨论】:
-
您能否也为
2 x 4矩阵或4 x 2添加预期输出 -
2x4 看起来像:1 2 5 7 4 3 6 8 4x2 看起来像:1 2 4 3 5 6 7 8