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 ] ]
Subscribe to see which companies asked this question
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int len = n*n;
int rows = n, cols = n;
vector<vector<int> > matrix(n, vector<int>(n, 0));
int beginRow=0, endRow=rows-1, beginCol=0, endCol=cols-1;
int cnt = 0;
for(; beginRow <= endRow && beginCol <= endCol; beginRow++, endRow--, beginCol++, endCol--) {
int tempCol = beginCol;
while(tempCol <= endCol) {
matrix[beginRow][tempCol] = cnt+1;
cnt++;
tempCol++;
}
int tempRow = beginRow+1;
while(tempRow <= endRow) {
matrix[tempRow][endCol] = cnt+1;
cnt++;
tempRow++;
}
tempCol = endCol-1;
while(tempCol >= beginCol) {
matrix[endRow][tempCol] = cnt+1;
cnt++;
tempCol--;
}
tempRow = endRow-1;
while(tempRow > beginRow) {
matrix[tempRow][beginCol] = cnt+1;
cnt++;
tempRow--;
}
}
return matrix;
}
};