-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
30 lines (29 loc) · 891 Bytes
/
Solution.java
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
public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int left = 0;
int right = n - 1;
int top = 0;
int bottom = n - 1;
int count = 0;
while(count < n * n) {
for (int i = left; i <= right && count < n*n; i++) {
res[top][i] = ++count;
}
for (int i = top + 1; i < bottom && count < n*n; i++) {
res[i][right] = ++count;
}
for (int i = right; i >= left && count < n*n; i--) {
res[bottom][i] = ++count;
}
for (int i = bottom - 1; i > top && count < n*n; i--) {
res[i][left] = ++count;
}
left++;
right--;
top++;
bottom--;
}
return res;
}
}