Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
就是leetcode 54Spiral Matrix【贪吃蛇】反回来而已
用上次第二种代码1A了
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n,vector<int>(n,0));
int sx=0,sy=0,ex=n-1,ey=n-1;
int tot=1;
while(sx<=ex){
for(int i=sy;i<=ey;i++)
ans[sx][i]=tot++;
for(int i=sx+1;i<=ex;i++)
ans[i][ey]=tot++;
for(int i=ey-1;i>=sy;i--)
ans[ex][i]=tot++;
for(int i=ex-1;i>=sx+1;i--)
ans[i][sy]=tot++;
sx++,sy++;
ex--,ey--;
}
return ans;
}
};