We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 67ef614 commit 9ec1f33Copy full SHA for 9ec1f33
java/0059-spiral-matrix-ii.java
@@ -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