[LeetCode]Spiral Matrix II
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 ] ]
思考:ACM蛇形填数。
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > res; if(n==0) return res; res.resize(n); for(int k=0;k<n;k++) res[k].resize(n); int count=1; int i=0,j=0; res[0][0]=1; while(count<n*n) { while(j+1<n&&!res[i][j+1]) res[i][++j]=++count; while(i+1<n&&!res[i+1][j]) res[++i][j]=++count; while(j-1>=0&&!res[i][j-1]) res[i][--j]=++count; while(i-1>=0&&!res[i-1][j]) res[--i][j]=++count; } return res; } };