-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy path59.Spiral-Matrix-II.java
58 lines (51 loc) · 1.49 KB
/
59.Spiral-Matrix-II.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
char direction = 'r';
int x = 0, y = 0;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
ans[i][j] = 0;
}
}
for(int i=1; i<=n*n; i++){
ans[x][y]=i;
switch(direction){
case 'r':
if(y==n-1 || ans[x][y+1]!=0){
direction = 'd';
x++;
}else{
y++;
}
break;
case 'd':
if(x==n-1 || ans[x+1][y]!=0){
direction = 'l';
y--;
}else{
x++;
}
break;
case 'l':
if(y==0 || ans[x][y-1]!=0){
direction = 'u';
x--;
}else{
y--;
}
break;
case 'u':
if(x==0 || ans[x-1][y]!=0){
direction = 'r';
y++;
}else{
x--;
}
break;
default:
}
}
return ans;
}
}