-
Notifications
You must be signed in to change notification settings - Fork 0
/
59-SpiralMatrix2.java
39 lines (33 loc) · 981 Bytes
/
59-SpiralMatrix2.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
31
32
33
34
35
36
37
38
39
class Solution {
public int[][] generateMatrix(int n) {
int ans[][] = new int[n][n];
int colstart = 0;
int colend = ans[0].length-1;
int rowstart = 0;
int rowend = ans.length-1;
int count = 1;
while(rowstart<=rowend && colstart<=colend){
for(int i=colstart;i<=colend;i++){
ans[rowstart][i]=count;
count++;
}
rowstart++;
for(int i=rowstart;i<=rowend;i++){
ans[i][colend]=count;
count++;
}
colend--;
for(int i=colend;i>=colstart;i--){
ans[rowend][i]=count;
count++;
}
rowend--;
for(int i=rowend;i>=rowstart;i--){
ans[i][colstart]=count;
count++;
}
colstart++;
}
return ans;
}
}