美文网首页
59. Spiral Matrix II

59. Spiral Matrix II

作者: jecyhw | 来源:发表于2019-05-28 09:51 被阅读0次

    题目链接

    https://leetcode.com/problems/spiral-matrix-ii/

    解题思路

    54. Spiral Matrix一样

    代码

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> ans(n, vector<int>(n, 0));
            int count = 1;
            int up = 0, down = n - 1, left = 0, right = n - 1;
            while (up <= down && left <= right) {
                if (up < n) {
                    for (int i = left; i <= right; ++i) {
                        ans[up][i] = count++;
                    }
                    up++;
                }
    
                if (right >= 0) {
                    for (int i = up; i <= down; ++i) {
                        ans[i][right] = count++;
                    }
                    right--;
                }
    
                if (down >= up) {
                    for (int i = right; i >= left; --i) {
                        ans[down][i] = count++;
                    }
                    down--;
                }
    
                if (left <= right) {
                    for (int i = down; i >= up; --i) {
                        ans[i][left] = count++;
                    }
                    left++;
                }
            }
            return ans;
        }
    };
    

    相关文章

      网友评论

          本文标题:59. Spiral Matrix II

          本文链接:https://www.haomeiwen.com/subject/recrtctx.html