LeetCode 1219. Path with Maximum Gold【DFS】中等

这篇博客讨论了一种解决策略,即通过深度优先搜索(DFS)算法来确定在给定的金矿网格中获取最多黄金的路径。题目描述了一个包含黄金的网格,矿工可以按上下左右移动,但不能重复访问同一单元格或访问含有0黄金的单元格。提供的C++代码实现了DFS算法,能够在限定时间内找到最优解,表现出良好的时间和空间效率。

In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.

Return the maximum amount of gold you can collect under the conditions:

  • Every time you are located in a cell you will collect all the gold in that cell.
  • From your position, you can walk one step to the left, right, up, or down.
  • You can't visit the same cell more than once.
  • Never visit a cell with 0 gold.
  • You can start and stop collecting gold from any position in the grid that has some gold.

Example 1:

Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
 [5,8,7],
 [0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.

Example 2:

Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
 [2,0,6],
 [3,4,5],
 [0,3,0],
 [9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 15
  • 0 <= grid[i][j] <= 100
  • There are at most 25 cells containing gold.

题意:你要开发一座金矿,地质勘测学家已经探明了这座金矿中的资源分布,并用大小为 m * n 的网格 grid 进行了标注。每个单元格中的整数就表示这一单元格中的黄金数量;如果该单元格是空的,那么就是 0

为了使收益最大化,矿工需要按以下规则来开采黄金:

  • 每当矿工进入一个单元,就会收集该单元格中的所有黄金。
  • 矿工每次可以从当前位置向上下左右四个方向走。
  • 每个单元格只能被开采(进入)一次。
  • 不得开采(进入)黄金数目为 0 的单元格。
  • 矿工可以从网格中 任意一个 有黄金的单元格出发或者是停止。

解法 DFS

简单题:

class Solution {
private:
    int n, m;
    int dfs(vector<vector<int>>& g, int x, int y) {
        if (x < 0 || x >= n || y < 0 || y >= m || !g[x][y]) return 0;
        int v = g[x][y];
        g[x][y] = 0;
        int ans = v + max(dfs(g, x - 1, y), max(dfs(g, x + 1, y), max(dfs(g, x, y - 1), dfs(g, x, y + 1))));
        g[x][y] = v; //恢复现场
        return ans;
    }
public:
    int getMaximumGold(vector<vector<int>>& grid) {
        n = grid.size(), m = grid[0].size();
        int ans = 0;
        for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (grid[i][j]) ans = max(ans, dfs(grid, i, j));    
        return ans;
    }
};

运行效率如下:

执行用时:48 ms, 在所有 C++ 提交中击败了92.54% 的用户
内存消耗:7.1 MB, 在所有 C++ 提交中击败了83.33% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值