您的位置:首页 > 其它

LeetCode:Spiral Matrix II

2016-03-02 15:01 423 查看


Spiral Matrix II

Total Accepted: 48130 Total
Submissions: 140755 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 ]
]


Hide Tags
Array

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ret(n, vector<int>(n));
        int rowStart = 0, rowEnd = n-1;
        int colStart = 0, colEnd = n-1;
        int num = 1;
        while(num <= n*n) {
            for(int i=colStart;i<=colEnd;i++) // "→"
                ret[rowStart][i] = num++;
            rowStart++;
            for(int i=rowStart;i<=rowEnd;i++) // "↓"
                ret[i][colEnd] = num++;
            colEnd--;
            for(int i=colEnd;i>=colStart;i--) // "←"
                ret[rowEnd][i] = num++;
            rowEnd--;
            for(int i=rowEnd;i>=rowStart;i--) // "↑"
                ret[i][colStart] = num++;
            colStart++;
        }
        return ret;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: