LeetCode每日一题(1219. Path with Maximum Gold)

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.

 

开始的时候觉得应该用DP, 后来想了想,走的路线不同,每个格子的最大值也不同, 所以DP貌似行不通,只能暴力来了, 现在在想有没有可能用bitset来保存, 没有具体的思路,后面再想吧。

 

代码(Rust):

impl Solution {
    fn dfs(grid: &Vec<Vec<i32>>, i: usize, j: usize, mut visited: Vec<Vec<bool>>) -> i32 {
        visited[i][j] = true;
        let up = if i > 0 && grid[i - 1][j] > 0 && !visited[i - 1][j] {
            Solution::dfs(grid, i - 1, j, visited.clone())
        } else {
            0
        };
        let down = if i < grid.len() - 1 && grid[i + 1][j] > 0 && !visited[i + 1][j] {
            Solution::dfs(grid, i + 1, j, visited.clone())
        } else {
            0
        };
        let left = if j > 0 && grid[i][j - 1] > 0 && !visited[i][j - 1] {
            Solution::dfs(grid, i, j - 1, visited.clone())
        } else {
            0
        };
        let right = if j < grid[0].len() - 1 && grid[i][j + 1] > 0 && !visited[i][j + 1] {
            Solution::dfs(grid, i, j + 1, visited.clone())
        } else {
            0
        };
        grid[i][j] + vec![up, down, left, right].into_iter().max().unwrap()
    }

    pub fn get_maximum_gold(grid: Vec<Vec<i32>>) -> i32 {
        let mut ans = 0;
        for i in 0..grid.len() {
            for j in 0..grid[0].len() {
                if grid[i][j] > 0 {
                    let visited = vec![vec![false; grid[0].len()]; grid.len()];
                    ans = ans.max(Solution::dfs(&grid, i, j, visited));
                }
            }
        }
        ans
    }
}

没什么需要过多解释的, 大家自己看吧

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值