-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution0059.java
More file actions
38 lines (33 loc) · 952 Bytes
/
Copy pathSolution0059.java
File metadata and controls
38 lines (33 loc) · 952 Bytes
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
// 59. 螺旋矩阵 II
/*
思路同“54.螺旋矩阵”
*/
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int left = 0, right = n - 1, top = 0, bottom = n - 1, num = 1;
while (true) {
for (int i = left; i <= right; i++) {
matrix[top][i] = num++;
}
top++;
if (top > bottom) break;
for (int i = top; i <= bottom; i++) {
matrix[i][right] = num++;
}
right--;
if (left > right) break;
for (int i = right; i >= left; i--) {
matrix[bottom][i] = num++;
}
bottom--;
if (top > bottom) break;
for (int i = bottom; i >= top; i--) {
matrix[i][left] = num++;
}
left++;
if (left > right) break;
}
return matrix;
}
}