59. Spiral Matrix II

来源:互联网 发布:c语言各种符号 编辑:程序博客网 时间:2024/05/02 00:29

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> > vec(n,vector<int>(n,0));        int i=0,j=0;        int currentValue = 1;        while(currentValue <= n*n)        {            for(;j<n;j++)            {                if(vec[i][j]!=0)                    break;                else                    vec[i][j]= currentValue++;            }            j--;            i++;            for(;i<n;i++)            {                if(vec[i][j]!=0)                    break;                else                    vec[i][j]= currentValue++;            }            i--;            j--;            for(;j>=0;j--)            {                if(vec[i][j]!=0)                    break;                else                    vec[i][j]= currentValue++;            }            j++;            i--;            for(;i>=0;i--)            {                if(vec[i][j]!=0)                    break;                else                    vec[i][j]= currentValue++;            }            i++;            j++;        }            return vec;    }};


0 0
原创粉丝点击