Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
蛇形填数,之前有一道类似的题。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>>ans(n, vector<int>(n));
int x = 0, y = 0, res = 0;
while(true)
{
for(int i=y; i<n-y; ++ i)
ans[x][i] = ++ res;
if(2*x + 1 >= n)
break;
for(int i=x+1; i<n-x; ++ i)
ans[i][n-y-1] = ++ res;
if(2*y + 1 >= n)
break;
for(int i=n-y-2; i >= y; -- i)
ans[n-x-1][i] = ++ res;
if(2*x + 2 == n)
break;
for(int i=n-x-2; i > x; -- i)
ans[i][y] = ++ res;
if(2*y + 2 == n)
break;
x ++, y ++;
}
return ans;
}
};