../ Competitive Programming
-rw-r--r--aguang1.1 KiB1 min read

Leet Code Daily 2024-08-08 - Spiral Matrix III

Code

c++
const vector<pair<int, int>> kDir = {
    {0, +1},
    {+1, 0},
    {0, -1},
    {-1, 0},
};

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart,
                                        int cStart) {
        auto inBounds = [&](const int r, const int c) -> bool {
            return r >= 0 && r < rows && c >= 0 && c < cols;
        };
        auto ret = vector<vector<int>>{
            vector<int>{rStart, cStart},
        };
        const int area = rows * cols;
        for (int step = 1, r = rStart, c = cStart; ret.size() < area;
             step += 2) {
            for (int k = 0; k < 4; k++) {
                for (int p = 0; p < (step + (k < 2 ? 0 : 1)); p++) {
                    const auto dir = kDir[k];
                    r += dir.first;
                    c += dir.second;
                    if (inBounds(r, c)) {
                        ret.push_back(vector<int>{r, c});
                    }
                }
            }
        }
        return ret;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window