您的位置:首页 > 其它

59. Spiral Matrix II

2017-07-30 17:23 417 查看
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<int> tmp;

        vector<vector<int>> res;

        

        if(n==0)

            return res;

        

        for(int i=0;i<n;i++){

            tmp.push_back(0);

        }

        for(int i=0;i<n;i++){

            res.push_back(tmp);

        }

        int nr=n,nc=n;

        vector<vector<int>> dir{{0,1},{1,0},{0,-1},{-1,0}};

        int ndir=0;

        vector<int> edge{nc,nr-1};
        //int x=0,y=0,count=1; 当y初始设为0的话,报错,越界错误

        int x=0,y=-1,count=1;

        

        while(edge[ndir%2]){

            for(int i=0;i<edge[ndir%2];i++){

                x+=dir[ndir%4][0];

                y+=dir[ndir%4][1];

                res[x][y]=count;

                count++;

            }

            edge[ndir%2]--;

            ndir=(ndir+1)%4;

        }

        return res;

        

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: