59. Spiral Matrix II

题目链接

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

解题思路

和54. Spiral Matrix一样

代码

class Solution {
public:
    vector> generateMatrix(int n) {
        vector> ans(n, vector(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)