LeetCode1219. 黃金礦工

1219. Path with Maximum Gold

In a gold mine grid of size m * 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:

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

題目:你要開發一座金礦,地質勘測學家已經探明瞭這座金礦中的資源分佈,並用大小爲 m * n 的網格 grid 進行了標註。每個單元格中的整數就表示這一單元格中的黃金數量;如果該單元格是空的,那麼就是 0。爲了使收益最大化,礦工需要按以下規則來開採黃金:

  • 每當礦工進入一個單元,就會收集該單元格中的所有黃金。
  • 礦工每次可以從當前位置向上下左右四個方向走。
  • 每個單元格只能被開採(進入)一次。
  • 不得開採(進入)黃金數目爲 0 的單元格。
  • 礦工可以從網格中 任意一個 有黃金的單元格出發或者是停止。

思路:DFS.

工程代碼下載 GitHub

class Solution {
public:
    int getMaximumGold(vector<vector<int>>& grid) {
        int r = grid.size();
        int c = grid[0].size();
        int res = 0;

        for(int i = 0; i < r; ++i)
            for(int j = 0; j < c; ++j)
                if(grid[i][j])
                    res = max(res, dfs(grid, i, j));

        return res;
    }
private:
    int dr[4] = {-1, 0, 1, 0};
    int dc[4] = {0, 1, 0, -1};
private:
    int dfs(vector<vector<int>>& grid, int i, int j){
        int r = grid.size();
        int c = grid[0].size();
        if(i < 0 || i >= r || j < 0 || j >= c || grid[i][j] <= 0)
            return 0;

        grid[i][j] = - grid[i][j];   // 標記已經走過了

        int res = 0;
        // 求解四個方向的最大值路徑
        for(int k = 0; k < 4; ++k){
            int x = i + dr[k];
            int y = j + dc[k];
            res = max(res, dfs(grid, x, y));
        }

        grid[i][j] = -grid[i][j];

        return res + grid[i][j];
    }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章