题目
59. 螺旋矩阵 II
题解
对于 3 * 3 的矩阵,
m[0][0] = 1, num = 2;
m[0][1] = 2, num = 3;
m[0][2] = 3, num = 4;
top = 1;
m[1][2] = 4, num = 5;
m[2][2] = 5, num = 6;
right = 1;
m[2][1] = 6, num = 7;
m[2][0] = 7, num = 8;
bottom = 1;
m[1][0] = 8, num = 9;
left = 1;
m[1][1] = 9, num = 10;
top = 2;
right = 0;
bottom = 0;
left = 2;
结束.
代码
import java.util.*;
public class code59 {
public static int[][] generateMatrix(int n) {
int left = 0, top = 0, right = n - 1, bottom = n - 1;
int m[][] = new int[n][n];
int tar = n * n;
int num = 1;
while (num <= tar) {
for (int i = left; i <= right; i++) {
m[top][i] = num;
num++;
}
top++;
for (int i = top; i <= bottom; i++) {
m[i][right] = num;
num++;
}
right--;
for (int i = right; i >= left; i--) {
m[bottom][i] = num;
num++;
}
bottom--;
for (int i = bottom; i >= top; i--) {
m[i][left] = num;
num++;
}
left++;
}
return m;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
int res[][] = generateMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%2d ", res[i][j]);
}
System.out.println();
}
}
}
}
参考
Spiral Matrix II (模拟法,设定边界,代码简短清晰)