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

Leet Code Daily 2024-05-14 - Path with Maximum Gold

Solution

DFS

Code

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

class Solution {
public:

    int ans = 0;

    void dfs(vector<vector<int>>& grid, int x, int y, int gold) {
        ans = max(ans, gold);
        for (const auto &d : kDir) {
            int nx = x + d.first;
            int ny = y + d.second;
            if (nx >= 0 && nx < grid.size() && ny >= 0 && ny < grid[0].size()) {
                int current = grid[nx][ny];
                if (current > 0) {
                    grid[nx][ny] = 0;
                    dfs(grid, nx, ny, gold + current);
                    grid[nx][ny] = current;
                }
            }
        }
    }

    int getMaximumGold(vector<vector<int>>& grid) {
        for (int x = 0; x < grid.size(); x++) {
            for (int y = 0; y < grid[0].size(); y++) {
                int current = grid[x][y];
                if (current > 0) {
                    grid[x][y] = 0;
                    dfs(grid, x, y, current);
                    grid[x][y] = current;
                }
            }
        }
        return ans;
    }
};

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