iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0

Medium
Related Topics: Array / Matrix / Simulation
LeetCode Source

解題想法

首先設定每次尋訪的方向在 vector<vector<int>> directions 裡頭

每次執行 2 次時,會增加走訪的長度 steps

接著就是從 rStartcStart 開始尋訪

[rStart, cStart] 有在規範的範圍內時

紀錄 count 跟將此位置存在 vector<vector<int>> res 裡頭

持續紀錄直到 countrow * cols 一樣時

最後回傳 res

Complexity

Time Complexity: O(rows * cols)
Space Complexity: O(rows * cols)

Python

class Solution:
    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
        res = []
        count = 0
        steps = 1
        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        d = 0 

        res.append([rStart, cStart])
        count += 1

        while count < rows * cols:
            for _ in range(2):
                for _ in range(steps):
                    rStart += directions[d][0]
                    cStart += directions[d][1]
                    if 0 <= rStart < rows and 0 <= cStart < cols:
                        res.append([rStart, cStart])
                        count += 1
                d = (d + 1) % 4
            steps += 1

        return res

C++

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        vector<vector<int>> res;
        int count = 0, steps = 1, d = 0;
        vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

        res.push_back({rStart, cStart});
        count += 1;

        while (count < rows * cols) {
            for (int i = 0; i < 2; i++) {
                for (int i = 0; i < steps; i++) {
                    rStart += directions[d][0];
                    cStart += directions[d][1];
                    if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {
                        res.push_back({rStart, cStart});
                        count += 1;
                    }
                }
                d = (d + 1) % 4;
            }
            steps += 1;
        }

        return res;
    }
};

上一篇
[8/7] 273. Integer to English Words
下一篇
[8/9] 840. Magic Squares In Grid
系列文
8月 LeetCode Daily 見聞錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言