LeetCode-59-螺旋矩陣 II


題意描述:

給定一個正整數 n,生成一個包含 1 到 n2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。


示例:

輸入: 3
輸出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

解題思路:

Alice: 我明白了,😎,LeetCode裏面題目後面加了一個 II 的並不意味這 要比原來的題目難。
Bob: 哈哈哈,也許就像這題一樣,這是換湯不換藥而已。
Alice: 那個圖再貼一下吧。
在這裏插入圖片描述
Bob: 好的。😎


代碼:

Python 方法一:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:

        i = 0;
        j = -1;
        idxs = -1
        clos = n
        rows = n
        cnt = 1
        tot = n*n
        ans = [[0 for x in range(n)] for z in range(n)]
        directions = [[0,1], [1,0], [0, -1], [-1, 0]]

        while cnt <= tot:

            idxs = (idxs + 1) % 4
            for x in range(clos):
                i += directions[idxs][0]
                j += directions[idxs][1]
                ans[i][j] = cnt
                cnt += 1
            rows -= 1

            idxs = (idxs + 1) % 4
            for x in range(rows):
                i += directions[idxs][0]
                j += directions[idxs][1]
                ans[i][j] = cnt
                cnt += 1
            clos -= 1

        return ans

Java 方法一: 螺旋訪問數組,填充元素。

class Solution {
    public int[][] generateMatrix(int n) {

        int[][] ans = new int[n][n];
        int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
        int i = 0;
        int j = -1;
        // 二維數組的下標
        int idx = -1;
        // directions 數組的下標
        int cnt = 1;
        int tot = n * n;
        int cols = n;
        int rows = n;

        while(cnt <= tot){

            // 橫向
            idx = (idx+1) % 4;
            for(int x=0; x<cols; ++x){
                i += directions[idx][0];
                j += directions[idx][1];
                ans[i][j] = cnt;
                cnt += 1;
            }
            rows -= 1;

			// 縱向
            idx = (idx + 1) % 4;
            for(int x=0; x<rows; ++x){
                i += directions[idx][0];
                j += directions[idx][1];
                ans[i][j] = cnt;
                cnt += 1;
            }
            cols -= 1;
        }

        return ans;
    }
}

易錯點:

  • 一些測試用例:
1
2
3
4
  • 答案:
[[1]]
[[1,2],[4,3]]
[[1,2,3],[8,9,4],[7,6,5]]
[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]

總結:

在這裏插入圖片描述


發佈了169 篇原創文章 · 獲贊 39 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章