[Leetcode]Spiral MatrixII

Spiral Matrix II My Submissions Question
Total Accepted: 41348 Total Submissions: 125636 Difficulty: Medium
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 ]
]
Subscribe to see which companies asked this question

Show Tags
Show Similar Problems

还是按照上一题的步骤去做好了 ,只有一点小改动

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> >    res(n,vector<int>(n,0));
        if(!n)  return res;
        int i = 0;
        int colBegin = 0;
        int colEnd = n - 1;
        int rowBegin = 0;
        int rowEnd = n - 1;
        while(colBegin <= colEnd && rowBegin <= rowEnd){
            for(int c = colBegin;c <= colEnd;++c){
                res[rowBegin][c] = ++i;
            }
            ++rowBegin;
            for(int r = rowBegin;r <= rowEnd;++r){
                res[r][colEnd] = ++i;
            }
            --colEnd;
            if(rowBegin <= rowEnd){
                for(int c = colEnd;c >= colBegin;--c){
                    res[rowEnd][c] = ++i;
                }
            }
            --rowEnd;
            if(colBegin <= colEnd){
                for(int r = rowEnd;r >= rowBegin;--r){
                    res[r][colBegin] = ++i;
                }
            }
            ++colBegin;
        }
        return res;
    }
};

posted on 2015-11-16 19:57  泉山绿树  阅读(23)  评论(0)    收藏  举报

导航