【LeetCode】59. Spiral Matrix II

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

 

Spiral Matrix实现基本一致,只不过上题是遍历输出,这题是遍历输入。

由于这题保证是方阵,因此不用考虑Spiral Matrix中重复扫描行/列的问题。

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        int layer = (n+1)/2;
        vector<vector<int> > ret(n, vector<int>(n, 0));
        int num = 1;
        for(int i = 0; i < layer; i ++)
        {
            //top-left --> top-right
            for(int j = i; j < n-i; j ++)
                ret[i][j] = num ++;
            //top-right --> bottom-right
            for(int j = i+1; j < n-i; j ++)
                ret[j][n-1-i] = num ++;
            //bottom-right --> bottom-left
            for(int j = n-1-i-1; j >= i; j --)
                ret[n-1-i][j] = num ++;
            //bottom-left --> top-left
            for(int j = n-1-i-1; j > i; j --)
                ret[j][i] = num ++;
        }
        return ret;
    }
};

posted @ 2014-12-11 13:37  陆草纯  阅读(140)  评论(0编辑  收藏  举报