Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
For example,
Given n =3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution {
public int[][] generateMatrix(int n) {
int max = n*n;
int num = 1;
int rowb = 0,rowe = n-1;
int colb = 0,cole = n-1;
int [][]res = new int[n][n];
while(rowb<=rowe&&colb<=cole){
for(int i=rowb;i<=rowe;i++){
res[rowb][i] = num;
num++;
}
rowb++;
for(int i=rowb;i<=rowe;i++){
res[i][cole] = num;
num++;
}
cole--;
if(rowe>=rowb){
for(int i = cole;i>=colb;i--){
res[rowe][i] = num;
num++;
}
}
rowe--;
if(cole>=colb){
for(int i=rowe;i>=rowb;i--){
res[i][colb] = num;
num++;
}
}
colb++;
}
return res;
}
}