其他分享
首页 > 其他分享> > leetcode_1293. Shortest Path in a Grid with Obstacles Elimination_[dp动态规划]

leetcode_1293. Shortest Path in a Grid with Obstacles Elimination_[dp动态规划]

作者:互联网

题目链接

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:

  


 

题意:给定一个矩阵,能向上下左右移动,问从[0, 0]走到[n-1, m-1]且在途中最多消除k个障碍的最少步数。

解法:很明显的动态规划题。朴素dfs会有大量重复的计算,使用动态规划存贮已经计算过的结果,避免重复计算。

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;
    }
};

 

标签:int,Obstacles,ret,41,grid,path,Grid,dp
来源: https://www.cnblogs.com/jasonlixuetao/p/12046501.html