Total Accepted: 48130
Total Submissions: 140755
Difficulty: Medium
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 ] ]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ret(n, vector<int>(n));
int rowStart = 0, rowEnd = n-1;
int colStart = 0, colEnd = n-1;
int num = 1;
while(num <= n*n) {
for(int i=colStart;i<=colEnd;i++) // "→"
ret[rowStart][i] = num++;
rowStart++;
for(int i=rowStart;i<=rowEnd;i++) // "↓"
ret[i][colEnd] = num++;
colEnd--;
for(int i=colEnd;i>=colStart;i--) // "←"
ret[rowEnd][i] = num++;
rowEnd--;
for(int i=rowEnd;i>=rowStart;i--) // "↑"
ret[i][colStart] = num++;
colStart++;
}
return ret;
}
};