Daily Leetcode - 59. Spiral Matrix II

Medium 螺旋矩陣2

2023 Dec LC challenge

題目 59. Spiral Matrix II

代碼隨想錄-螺旋矩陣 螺旋矩陣 : 注意邊界問題

  • 左閉右開 (本題用這個)
  • 左閉右閉
  • 那如果要循環? 要轉幾圈? 題目給 n ,假設 n = 4 ,每轉一圈少兩行所以 n / 2 = 2 (另一個說法)
  • 方陣

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
class Solution {
    public int[][] generateMatrix(int n) {
        int loop = 0; 
        int[][] res = new int[n][n];
        int start = 0; 
        int count = 1; 
        int i, j;
        while(loop < n / 2) {
             loop++;
            for (j = start; j < n - loop; j++) {
                res[start][j] = count++;
            }

            for (i = start; i < n - loop; i++) {
                res[i][j] = count++;
            }

            for (; j >= loop; j--) {
                res[i][j] = count++;
            }

            for (; i >= loop; i--) {
                res[i][j] = count++;
            }
           
            start++;
        }
        if (n % 2 == 1) {
           res[start][start] = count;
        }
        return res;
    }
}
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus