-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode_00059.java
More file actions
42 lines (39 loc) · 1.16 KB
/
LeetCode_00059.java
File metadata and controls
42 lines (39 loc) · 1.16 KB
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
41
42
package com.github.jerring.leetcode;
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;
}
}