Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1293. Shortest Path in a Grid with Obstacles Elimination

Rain Hu

1293. Shortest Path in a Grid with Obstacles Elimination


一、題目

You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacles). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right conrer 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:
short1-grid

Example 2: short2-grid

Constraints:


二、分析

三、解題

1. BFS

int dirc[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
int shortestPath(vector<vector<int>>& grid, int k) {
    int m = grid.size(), n = grid[0].size();
    vector<vector<int>> visited(m, vector<int>(n, -1));  // 餘愈多愈好,故預設為 -1
    queue<vector<int>> q; // {row, col, len, k}
    q.push({0,0,0,k});
    
    while (!q.empty()) {
        auto info = q.front();
        q.pop();
        int row = info[0];
        int col = info[1];
        int len = info[2];
        int bomb = info[3];
        
        // 超出範圍 out of bound
        if (row < 0 || col < 0 || row >= m || col >= n) continue;
        
        // 終止條件,到達右下角 
        if (row == m-1 && col == n-1) return len;
        
        // 遇到障礙物
        if (grid[row][col] == 1) {
            if (bomb > 0) 
                bomb--;
            else 
                continue;
        }
        
        // 減枝:拜訪過且剩餘次數較少者跳過
        if (visited[row][col] >= bomb) continue;
        visited[row][col] = bomb;
        
        // 將下一步加入佇列
        for (const auto& d : dirc){
            q.push({row+d[0], col+d[1], len+1, bomb});
        }
    }
    return -1;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 19. Remove Nth Node From End of List
Next
[LeetCode] 2953. Count Complete Substrings