作业帮 > 综合 > 作业

java 算法题 输入一个数n,输出n阶矩阵为:如n=3,矩阵为:1 2 38 9 47 6 5如n=4,矩阵为:1 2

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/25 11:51:46
java 算法题
输入一个数n,输出n阶矩阵为:
如n=3,矩阵为:
1 2 3
8 9 4
7 6 5
如n=4,矩阵为:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
private static void printArray(int n) {
int[][] a = new int[n][n];
int row = 0;
int col = 0;
int tempRow = 0;
int tempCol = 0;
boolean isButtom = false;
for (int i = 1; i = 0 && a[tempRow][col] == 0) {
row = tempRow;
continue;
}
}

//尝试向右
tempCol = col + 1;
if (tempCol < n && a[row][tempCol] == 0) {
col = tempCol;
isButtom = false;
continue;
}

//尝试向下
tempRow = row + 1;
if (tempRow < n && a[tempRow][col] == 0) {
row = tempRow;
isButtom = false;
continue;
}

//尝试向左
tempCol = col - 1;
if (tempCol >= 0 && a[row][tempCol] == 0) {
col = tempCol;
isButtom = true;
continue;
}

//尝试向上
tempRow = row - 1;
if (tempRow >= 0 && a[tempRow][col] == 0) {
row = tempRow;
isButtom = false;
continue;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}