LeetCode59-螺旋矩阵II

题目链接

英文链接:https://leetcode.com/problems/spiral-matrix-ii/

中文链接:https://leetcode-cn.com/problems/spiral-matrix-ii/

题目详述

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

1
2
3
4
5
6
7
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

题目详解

LeetCode54-螺旋矩阵 类似,都是按层进行处理,处理完一层,再处理下一层。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class LeetCode_00059 {

public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int top = 0, bottom = n - 1;
int left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right) {
num = fillEdge(res, top++, bottom--, left++, right--, num);
}
return res;
}

private int fillEdge(int[][] res, int top, int bottom, int left, int right, int num) {
if (top == bottom) {
for (int i = left; i <= right; ++i) {
res[top][i] = num++;
}
} else if (left == right) {
for (int i = top; i <= bottom; ++i) {
res[i][right] = num++;
}
} else {
int i = top, j = left;
while (j != right) {
res[i][j++] = num++;
}
while (i != bottom) {
res[i++][j] = num++;
}
while (j != left) {
res[i][j--] = num++;
}
while (i != top) {
res[i--][j] = num++;
}
}
return num;
}
}