59. 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 ]
]
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>>ans(n,vector<int>(n));
        int l=0,r=n-1,u=0,d=n-1,id=1;
        while(l<r&&u<d){
           // cout<<l<<' '<<u<<' '<<r<<' '<<d<<' '<<endl;
            //up
            for(int j=l;j<r;j++)
                ans[u][j]=id++;
            //right
            for(int j=u;j<d;j++)
                ans[j][r]=id++;
            //down
            for(int j=r;j>l;j--)
                ans[d][j]=id++;
            //left
            for(int j=d;j>u;j--)
                ans[j][l]=id++;
            l++,r--,u++,d--;
        }
        if(n&1)ans[n/2][n/2]=n*n;
        return ans;
    }
};

 

posted @ 2017-04-06 14:31  Tsunami_lj  阅读(102)  评论(0编辑  收藏  举报