forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiralmatrix2.java
More file actions
executable file
·37 lines (35 loc) · 962 Bytes
/
spiralmatrix2.java
File metadata and controls
executable file
·37 lines (35 loc) · 962 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
public class Solution {
private boolean withinBound(int x, int y, int n){
return x>=0 && y>=0 && x<n && y<n;
}
public int[][] generateMatrix(int n) {
// Start typing your Java solution below
// DO NOT write main() function
int i=1;
int nn = n*n;
int[][] ans = new int[n][n];
int x =0;
int y =0;
int dirx = 0;
int diry = 1;
while(i<=nn){
ans[x][y] = i;
if(i==nn) break;
int newx = x+dirx;
int newy = y+diry;
if(withinBound(newx,newy,n) && ans[newx][newy]==0 ){
x = newx;
y = newy;
}else{
int newdirx = diry;
int newdiry = -dirx;
dirx = newdirx;
diry = newdiry;
x = x+dirx;
y = y+diry;
}
i++;
}
return ans;
}
}