leetcode No59. Spiral Matrix II

来源:互联网 发布:第八届中国云计算大会 编辑:程序博客网 时间:2024/05/22 15:08

Question:

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 ]]

Accepted Code:

class Solution {public:    vector<vector<int>> generateMatrix(int n) {        vector<vector<int>> res(n,vector<int>(n,0));        if(n==0)return res;        int count=0;        int value=1;        while(count<(n/2))        {            for(int j=count;j<n-count;j++)            {                res[count][j]=value;                value++;            }            for(int i=count+1;i<n-count;i++)            {                res[i][n-count-1]=value;                value++;            }            for(int j=n-count-2;j>=count;j--)            {                res[n-count-1][j]=value;                value++;            }            for(int i=n-count-2;i>count;i--)            {                res[i][count]=value;                value++;            }            count++;        }        if(n%2==1)            res[count][count]=value;                return res;    }};


0 0
原创粉丝点击