LeetCode题目:Spiral Matrix II

原题地址:https://leetcode.com/problems/spiral-matrix-ii/

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        if(0 == n){
            vector<vector<int>> coll;
            return coll;
        }
        vector<vector<int>> coll(n, vector<int>(n, 1));
        int num = 1;
        for(int i = 0; i < n - 1; ++i){
            for(int j = i; j < n - i; ++j)
                coll[i][j] = num++;
            for(int j = i + 1; j < n - i; ++j)
                coll[j][n - i -1] = num++;
            for(int j = n - i - 2; j >= i; --j)
                coll[n - i - 1][j] = num++;
            for(int j = n - i - 2; j >= i + 1; --j)
                coll[j][i] = num++;
        }
        return coll;
    }
};

 

posted @ 2016-03-08 11:38  Runnyu  阅读(185)  评论(0编辑  收藏  举报