现在的位置: 首页 > 综合 > 正文

Spiral Matrix II

2018年04月01日 ⁄ 综合 ⁄ 共 556字 ⁄ 字号 评论关闭

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

思路:同spiral I
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > a;
        if (n<=0) {
            return a;
        }
        vector<vector<int> > res(n, vector<int>(n, 0));
        int i=0,j,num=0;
        while(2*i<n) {
            for(j=i; j<n-i; ++j) {
                num++;
                res[i][j] = num;
            }
            for(j=i+1; n-i-1>i&&j<n-i; ++j) {
                num++;
                res[j][n-i-1] = num;
            }
            for(j=n-i-2; i<n-i-1&&j>=i; --j) {
                num++;
                res[n-i-1][j] = num;
            }
            for(j=n-i-2; j>i; --j) {
                num++;
                res[j][i] = num;
            }
            ++i;
        }
        return res;
    }
};

抱歉!评论已关闭.