[LeetCode] 59. Spiral Matrix II 螺旋矩陣之二


 

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

Example:

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

此題跟之前那道 Spiral Matrix 本質上沒什么區別,就相當於個類似逆運算的過程,這道題是要按螺旋的順序來填數,由於給定矩形是個正方形,我們計算環數時用 n / 2 來計算,若n為奇數時,此時最中間的那個點沒有被算在環數里,所以最后需要單獨賦值,還是下標轉換問題是難點,參考之前 Spiral Matrix 的講解來轉換下標吧,參見代碼如下:

 

解法一:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n));
        int val = 1, p = n;
        for (int i = 0; i < n / 2; ++i, p -= 2) {
            for (int col = i; col < i + p; ++col)
                res[i][col] = val++;
            for (int row = i + 1; row < i + p; ++row)
                res[row][i + p - 1] = val++;
            for (int col = i + p - 2; col >= i; --col)
                res[i + p - 1][col] = val++;
            for (int row = i + p - 2; row > i; --row)    
                res[row][i] = val++;
        }
        if (n % 2 != 0) res[n / 2][n / 2] = val;
        return res;
    }
};

 

當然我們也可以使用下面這種簡化了坐標轉換的方法,博主個人還是比較推崇下面這種解法,不容易出錯,而且好理解,參見代碼如下:

 

解法二:

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

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/59

 

類似題目:

Spiral Matrix

 

參考資料:

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

https://leetcode.com/problems/spiral-matrix-ii/discuss/22392/C%2B%2B-template-for-Spiral-Matrix-and-Spiral-Matrix-II

https://leetcode.com/problems/spiral-matrix-ii/discuss/22289/My-Super-Simple-Solution.-Can-be-used-for-both-Spiral-Matrix-I-and-II

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM