Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
Solution:
I directly list 4 cases about how we proceed. The code is quite long but straightforward and clear.
Code:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
int cur_row = 0;
int cur_col = 0;
int upper_row = n-1;
int lower_row = 0;
int upper_col = n-1;
int lower_col = 0;
int count = 1;
while(count<=n*n){
res[cur_row][cur_col] = count;
if(cur_row == lower_row){//at the upper row
if(cur_col == upper_col){//should turn down
cur_row ++;
}else{//should go right
cur_col ++;
}
}else if(cur_col == upper_col){//at the right col
if(cur_row == upper_row){//should turn left
cur_col --;
}else{//should go down
cur_row ++;
}
}else if(cur_row == upper_row && upper_row != lower_row){//at the bottom
if(cur_col != lower_col){//should go left
cur_col --;
}else{//should turn up
cur_row --;
}
}else if(upper_col != lower_col){//cur_col == lower_col, at the left side
if(cur_row != lower_row + 1){//can go up
cur_row --;
}else{//go right to the next submatrix
cur_col ++;
upper_row --;
lower_row ++;
upper_col --;
lower_col ++;
}
}
count++;
}
return res;
}
};