Spiral Matrix II - shilpathota/99-leetcode-solutions GitHub Wiki
Spiral Matrix II
https://leetcode.com/problems/spiral-matrix-ii/
Leet Code Link -Complexity - Medium
Description
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
Input: n = 3
Output: [1,2,3],[8,9,4],[7,6,5](/shilpathota/99-leetcode-solutions/wiki/1,2,3],[8,9,4],[7,6,5)
Example 2:
Input: n = 1
Output: [1](/shilpathota/99-leetcode-solutions/wiki/1)
Constraints:
1 <= n <= 20
Solution
As it is spiral, when the value of row and col reaches the end the direction should change from col to row. First the row is constant and column increments and then row increments while col stays in the last column. Next the col decrements while row remains in end. At last row decrements as column is at the start. While this is happening we decrement and increment the row and col accordingly once visited.
This is repeated until rowstart exceeds rowEnd and colStart exceeds colEnd
class Solution {
public int[][] generateMatrix(int n) {
//variables
int[][] res = new int[n][n];
int cnt = 1;
int rowStart = 0,rowEnd = res.length-1;
int colStart = 0,colEnd = res[0].length-1;
while(rowStart<=rowEnd && colStart <=colEnd){
for(int i=colStart;i<=colEnd;i++){
res[rowStart][i]=cnt++;
}
rowStart++;
for(int i=rowStart;i<=rowEnd;i++){
res[i][colEnd]=cnt++;
}
colEnd--;
for(int i=colEnd;i>=colStart;i--){
res[rowEnd][i]=cnt++;
}
rowEnd--;
for(int i=rowEnd;i>=rowStart;i--){
res[i][colStart]=cnt++;
}
colStart++;
}
return res;
}
}