LeetCode 59. Spiral Matrix II

来源:互联网 发布:eagle软件下载 编辑:程序博客网 时间:2024/06/05 15:08

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) {        int tot=1,x=0,y=0;        vector<vector<int>> v(n,vector<int>(n));        if(n==1){            v[0][0]=1;            return v;        }        while(tot<n*n){            v[0][0]=1;            while(y+1<n&&!v[x][y+1]){                v[x][++y]=++tot;            }            while(x+1<n&&!v[x+1][y]){                v[++x][y]=++tot;            }            while(y-1>=0&&!v[x][y-1]){                v[x][--y]=++tot;               }            while(x-1>=0&&!v[x-1][y]){                v[--x][y]=++tot;            }        }        return v;    }};