59. Spiral Matrix II (Leetcode || Java)
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]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
1 <= n <= 20
SOLUTION:
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];//declaring matrix
int rStart = 0;
int rEnd = n — 1;
int cStart = 0;
int cEnd = n — 1;
int num = 1;
while(rStart <= rEnd && cStart <= cEnd && num <= n*n){
for(int i = cStart; i <= cEnd; i++){//filling first row
ans[rStart][i] = num;
num++;
}
rStart++;//As first row is filled eliminate that row
for(int j = rStart; j <= rEnd; j++){//filling last row
ans[j][cEnd] = num;
num++;
}
cEnd — ;
if(cStart <= cEnd){//filling inner last row
for(int j = cEnd; j >= cStart; j — ){
ans[rEnd][j] = num;
num++;
}
}
rEnd — ;//As last row is filled eliminate that row
if(rStart <= rEnd){//filling inner first column
for(int i = rEnd; i >= rStart; i — ){
ans[i][cStart] = num;
num++;
}
}
cStart++;//As first column is filled eliminate that column
}
return ans;
}
}