Daily Leetcode - 54. Spiral Matrix

Medium 螺旋矩陣

2023 Dec LC challenge

題目 54. Spiral Matrix

代碼隨想錄-螺旋矩陣 賈考博-leetcode 54 螺旋矩陣 : 注意邊界問題

  • 此題有課能為不對稱矩陣,需多加判斷,避免重複計算
  • 遍歷一行少一行,遍歷一列少一列,因為行列都有改變所以要多加判斷是否會重複遍歷

My Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix.length == 0 || matrix[0].length == 0) {
            return result;
        }
        int m = matrix.length; //row
        int n = matrix[0].length; //col
        int endRow = m - 1;
        int endCol = n - 1;
        int startx = 0; //(x, y)
        int starty = 0; //(x, y)
        int i;

        while(startx <= endRow && starty <= endCol) {
            for(i = starty; i <= endCol; i++) {
                result.add(matrix[startx][i]);
            }
            startx++;
            
            for(i = startx; i <= endRow; i++) {
                result.add(matrix[i][endCol]);
            }
            endCol--;
            if(startx <= endRow){
                for(i = endCol; i >= starty; i--) {
                    result.add(matrix[endRow][i]);
                }
                endRow--;
            }

            if(starty <= endCol){ //判斷 因為我們上面startx++;做了更動,沒檔可能又跑進來
                for(i = endRow; i >= startx; i--) {
                    result.add(matrix[i][starty]);
                }
                starty++;
            }

        } 
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus