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

 

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

Example:post

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

此題跟以前那道 Spiral Matrix 本質上沒什麼區別,就至關於個相似逆運算的過程,這道題是要按螺旋的順序來填數,因爲給定矩形是個正方形,咱們計算環數時用n / 2來計算,若n爲奇數時,此時最中間的那個點沒有被算在環數裏,因此最後須要單獨賦值,仍是下標轉換問題是難點,參考以前 Spiral Matrix 的講解來轉換下標吧,代碼以下:url

 

解法一:spa

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

 

固然咱們也能夠使用下面這種簡化了座標轉換的方法,博主我的仍是比較推崇下面這種解法,不容易出錯,並且好理解,參見代碼以下:code

 

解法二:htm

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

 

相似題目:blog

Spiral Matrixelement

 

參考資料:leetcode

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

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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索