1. 程式人生 > 其它 >[LeetCode] 59. Spiral Matrix II

[LeetCode] 59. Spiral Matrix II

[LeetCode] 59. Spiral Matrix 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. 按層模擬(一層一層的填)

程式碼

用模擬寫的,按層模擬見官方題解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;
    }
};

歡迎轉載,轉載請註明出處!