Leetcode_spiral-matrix-ii

来源:互联网 发布:淘宝买家号开店 编辑:程序博客网 时间:2024/06/04 04:28

地址:http://oj.leetcode.com/problems/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 ]]
思路:模拟题,跟上一题类似http://blog.csdn.net/flyupliu/article/details/22584219

先把vector用0填满了,循环次数控制在n*n范围内。

参考代码:

class Solution {public:    vector<vector<int> > generateMatrix(int n) {        vector<vector<int> >res;        if(!n)            return res;        n = n>0? n : -n;        for(int k = 0; k < n; ++k)        {            vector<int>tmpvec;            for(int p = 0; p < n; ++p)            {                tmpvec.push_back(0);            }            res.push_back(tmpvec);        }        int i = 0, j = 0, cnt = 1;        while(cnt <= n*n)        {            while(j<n && !res[i][j])                res[i][j++]=cnt++;            ++i;            --j;            while(i<n && !res[i][j])                res[i++][j]=cnt++;            --j;            --i;            while(j>=0 && !res[i][j])                res[i][j--]=cnt++;            --i;            ++j;            while(i>=0 && !res[i][j])                res[i--][j]=cnt++;            ++j;            ++i;        }        return res;    }};


//SECOND TRAIL
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> >ans;
        for(int i = 0; i<n; ++i)
        {
            vector<int>v(n, 0);
            ans.push_back(v);
        }
        int ib = 0, ie = n-1, jb = 0, je = n-1, val = 1;
        while(ib <= ie && jb <= je)
        {
            for(int j = jb; j<=je; ++j)
                ans[ib][j] = val++;
            ++ib;
            for(int i = ib; i<=ie; ++i)
                ans[i][je] = val++;
            --je;
            if(ib > ie || jb > je)
                break;
            for(int j = je; j >= jb; --j)
                ans[ie][j] = val++;
            --ie;
            for(int i = ie; i>=ib; --i)
                ans[i][jb] = val++;
            ++jb;
        }
        return ans;
    }
};


0 0