Skip to content

Commit

Permalink
Add 59_Spiral_Matrix_II.java
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Prashad authored and Sean Prashad committed Jan 16, 2020
1 parent aa59b42 commit 3db2cc3
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Matrix/59_Spiral_Matrix_II.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];

int minCol = 0, maxCol = n - 1, minRow = 0, maxRow = n - 1;
int no = 1;

while (minCol <= maxCol && minRow <= maxRow) {
for (int i = minCol; i <= maxCol; i++) {
res[minRow][i] = no++;
}
++minRow;

for (int i = minRow; i <= maxRow; i++) {
res[i][maxCol] = no++;
}
--maxCol;

if (minCol > maxCol || minRow > maxRow) {
break;
}

for (int i = maxCol; i >= minCol; i--) {
res[maxRow][i] = no++;
}
--maxRow;

for (int i = maxRow; i >= minRow; i--) {
res[i][minCol] = no++;
}
++minCol;
}

return res;
}
}

0 comments on commit 3db2cc3

Please sign in to comment.