[LeetCode] 59. 螺旋矩阵 II

[LeetCode] 59. 螺旋矩阵 II

题目

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

思路

  1. 模拟

  2. 按层模拟(一层一层的填)

相似题目:54. 螺旋矩阵

代码

用模拟写的,按层模拟见官方题解https://leetcode-cn.com/problems/spiral-matrix-ii/solution/luo-xuan-ju-zhen-ii-by-leetcode-solution-f7fp/

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int mni = 0, mxi = n - 1;
        int mnj = 0, mxj = n - 1;
        int i = 0, j = 0, di = 0, dj = 1;
        vector<vector<int>> ans;
        ans.resize(n);
        for (int i = 0; i < n; i++) {
            ans[i].resize(n);
        }
        int cur = 1;
        while(mni <= mxi && mnj <= mxj) {
            ans[i][j] = cur++;
            if (di == -1 && i == mni && j == mnj) {
                di = 0;
                dj = 1;
                mnj++;
            } else if (dj == 1 && i == mni && j == mxj) {
                di = 1;
                dj = 0;
                mni++;
            } else if (di == 1 && i == mxi && j == mxj) {
                di = 0;
                dj = -1;
                mxj--;
            } else if (dj == -1 && i == mxi && j == mnj) {
                di = -1;
                dj = 0;
                mxi--;
            }
            i += di;
            j += dj;
        }
        return ans;
    }
};

posted @ 2021-10-19 16:11  沐灵_hh  阅读(20)  评论(0编辑  收藏  举报