2026/03/06

[LeetCode] 54 Spiral Matrix

 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
class Solution {
public:
  vector<int> spiralOrder(vector<vector<int>>& matrix) {
    constexpr int MAX = 11;
    bool vis[MAX][MAX] = {0};
    
    vector<int> ans;
    int M = matrix.size();
    int N = matrix[0].size();

    auto isValid = [&](int x, int y) -> bool {
      return x >= 0 && x < M && y >=0 && y < N;
    };

    int dx[4] = {0, 1, 0, -1};
    int dy[4] = {1, 0, -1, 0};
    int x = 0;
    int y = 0;
    int i = 0;    
    while (true) {
      ans.push_back(matrix[x][y]);
      if (ans.size() == M * N)
        break;
        
      vis[x][y] = true;
      while (!isValid(x + dx[i], y + dy[i]) || vis[x + dx[i]][y + dy[i]]) 
        i = (i + 1) % 4;

      x = x + dx[i];
      y = y + dy[i];
    }
    return ans;
  }
};