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
}
}
没什么需要过多解释的, 大家自己看吧