Skip to content

Commit 346f46c

Browse files
authored
Merge pull request neetcode-gh#3310 from AmitSaha15/0059-spiral-matrix-ii
Create 0059-spiral-matrix-ii.java
2 parents f8d4920 + 9ec1f33 commit 346f46c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

java/0059-spiral-matrix-ii.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int[][] generateMatrix(int n) {
3+
int[][] ans = new int[n][n];
4+
5+
int r1=0, r2=n-1;
6+
int c1=0, c2=n-1;
7+
int elem = 1;
8+
while(r2>=r1 && c2>=c1){
9+
for(int i=c1; i<=c2; i++){
10+
ans[r1][i] = elem++;
11+
}
12+
for(int j=r1+1; j<=r2-1; j++){
13+
ans[j][c2] = elem++;
14+
}
15+
if(r2>r1 && c2>c1){
16+
for (int i = c2; i >= c1; i--){
17+
ans[r2][i] = elem++;
18+
}
19+
for (int j = r2-1; j>=r1+1; j--){
20+
ans[j][c1] = elem++;
21+
}
22+
}
23+
r1++;
24+
r2--;
25+
c1++;
26+
c2--;
27+
}
28+
return ans;
29+
}
30+
}

0 commit comments

Comments
 (0)