题目地址:https://leetcode-cn.com/problems/spiral-matrix-ii/
给你一个正整数 n
,生成一个包含 1 到
n
2
n^2
n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1
输出:[[1]]
提示:
1 <= n <= 20
public class LC59 {
public static void main(String[] args) {
int n = 5;
int[][] matrix = generateMatrix(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%4d ", matrix[i][j]);
}
System.out.println();
}
}
public static int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int topMargin = 0; // 上边界
int leftMargin = 0; // 右边界
int rightMargin = 0; // 右边界
int bottomMargin = 0; // 下边界
int val = 0; // 某位置的数值
while (val < n * n) {
for (int i = leftMargin; i < n - rightMargin; i++) {
val++;
matrix[topMargin][i] = val;
}
topMargin++;
for (int i = topMargin; i < n - bottomMargin; i++) {
val++;
matrix[i][n - 1 - rightMargin] = val;
}
rightMargin++;
for (int i = n - 1 - rightMargin; i >= leftMargin; i--) {
val++;
matrix[n - 1 - bottomMargin][i] = val;
}
bottomMargin++;
for (int i = n - 1 - bottomMargin; i >= topMargin; i--) {
val++;
matrix[i][leftMargin] = val;
}
leftMargin++;
}
return matrix;
}
}