classSolution: """ Simulation 從左上角開始,按照順時針方向依次填入數字,遇到邊界或已經填過的數字就轉向 """ defspiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: DIR = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 定義四個方向 ans = [[-1] * n for _ inrange(m)] # 初始化答案矩陣 x, y, cd = 0, 0, 0# 初始化起始位置和方向 while head isnotNone: ans[x][y] = head.val # 填入數字 head = head.next# 移動到鏈接串列的下一個節點 nx, ny = x + DIR[cd][0], y + DIR[cd][1] # 計算新位置 # 若新位置超出邊界或已經填過,則需要轉向 if (nx < 0or nx >= m or ny < 0or ny >= n or ans[nx][ny] != -1): cd = (cd + 1) % 4# 轉向 nx, ny = x + DIR[cd][0], y + DIR[cd][1] # 計算新位置 x, y = nx, ny # 更新位置 return ans
classSolution { public: vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) { vector<pair<int, int>> DIR = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector<vector<int>> ans(m, vector<int>(n, -1)); int x = 0, y = 0, cd = 0, nx, ny; while (head != nullptr) { ans[x][y] = head->val; head = head->next; nx = x + DIR[cd].first; ny = y + DIR[cd].second; if (nx < 0 || nx >= m || ny < 0 || ny >= n || ans[nx][ny] != -1) { cd = (cd + 1) % 4; nx = x + DIR[cd].first; ny = y + DIR[cd].second; } x = nx; y = ny; } return ans; } };
寫在最後
Cover photo is remixed from @吃肥皂泡泡, thanks for their work!