leetcode_1293. Shortest Path in a Grid with Obstacles Elimination_ [dp dynamic programming]

Topic Link

Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

 

Example 1:

Input: 
grid = 
[[0,0,0],
 [1,1,0],
 [0,0,0],
 [0,1,1],
 [0,0,0]], 
k = 1
Output: 6
Explanation: 
The shortest path without eliminating any obstacle is 10. 
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

 

Example 2:

Input: 
grid = 
[[0,1,1],
 [1,1,1],
 [1,0,0]], 
k = 1
Output: -1
Explanation: 
We need to eliminate at least two obstacles to find such a walk.

 

Constraints:

  • grid.length == m
  • grid[0].length == n
  • 1 <= m, n <= 40
  • 1 <= k <= m*n
  • grid[i][j] == 0 or 1
  • grid[0][0] == grid[m-1][n-1] == 0

  


 

The meaning of problems: Given a matrix, can be moved vertically and horizontally, from Q [0, 0] go to [n-1, m-1] and the minimum number of steps to eliminate most of the k-th obstacle on the way.

Solution: Obviously the dynamic programming problem. Dfs have a lot of repeat simple calculations using dynamic programming stored results have been calculated to avoid double counting.

int dirs[4][2] = {-1,0, 0,1,1,0,0,-1};
int dp[41][41][1700];
bool flag[41][41];
class Solution {
public:
    vector<vector<int>> _grid;

    bool inside(int x, int y){
        if(x>=0 && x<_grid.size() && y>=0 &&y<_grid[0].size())
            return true;
        return false;
    }

    int shortestPath(vector<vector<int>>& grid, int k) {
        _grid = grid;
        memset(dp, -1, sizeof(dp));
        memset(flag, 0 ,sizeof(flag));
        int ret = dfs(0, 0, k);
        return ret>=INT_MAX/2 ? -1 : ret;   
    }

    int dfs(int x, int y, int k){
        if(k<0)
            return INT_MAX/2;
        if(dp[x][y][k] != -1)
            return dp[x][y][k];
        if(x==_grid.size()-1 && y==_grid[0].size()-1)
            return dp[x][y][k] = 0;
        
        int ret = INT_MAX/2;
        for(int i=0; i<4; i++){
            int xx = x+dirs[i][0];
            int yy = y+dirs[i][1];
            if(inside(xx, yy) && !flag[xx][yy]){
                flag[xx][yy] = true;
                int temp = INT_MAX/2;
                if(_grid[xx][yy])
                    temp = dfs(xx, yy, k-1);
                else
                    temp = dfs(xx, yy, k);
                ret = min(ret, 1+temp);
                flag[xx][yy] = false;
            }
        }
        return dp[x][y][k] = ret;
    }
};

 

Guess you like

Origin www.cnblogs.com/jasonlixuetao/p/12046501.html