Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1293.html

1293. Shortest Path in a Grid with Obstacles Elimination (Hard)

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

Related Topics: Breadth-first Search

Solution 1. BFS

// OJ: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
// Time: O(MN * min(K, M + N))
// Space: O(MNK)
class Solution {
public:
    int shortestPath(vector<vector<int>>& G, int K) {
        int M = G.size(), N = G[0].size(), dp[40][40][80], seen[40][40][80] = {}, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
        memset(dp, 0x3f, sizeof(dp));
        if (K >= M + N - 3) return M + N - 2; // This line is super important.
        for (int k = 0; k <= K; ++k) {
            dp[M - 1][N - 1][k] = 0;
            queue<vector<int>> q;
            q.push({ M - 1, N - 1, 0, 0 });
            seen[M - 1][N - 1][k] = 1;
            while (q.size()) {
                auto pos = q.front();
                q.pop();
                int x = pos[0], y = pos[1], i = pos[2], val = pos[3];
                dp[x][y][k] = val;
                seen[x][y][k] = 1;
                for (auto &dir : dirs) {
                    int a = x + dir[0], b = y + dir[1];
                    if (a < 0 || b < 0 || a >= M || b >= N || seen[a][b][k] || i + (G[x][y] == 1) > k) continue;
                    seen[a][b][k] = 1;
                    q.push({ a, b, i + (G[x][y] == 1), val + 1 });
                }
            }
        }
        return dp[0][0][K] >= 0x3f3f3f3f ? -1 : dp[0][0][K];
    }
};

Solution 2. BFS

// OJ: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
// Time: O(MN * min(K, M + N))
// Space: O(MNK)
// Ref: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/451787/Python-O(m*n*k)-BFS-Solution-with-Explanation
class Solution {
public:
    int shortestPath(vector<vector<int>>& G, int K) {
        int M = G.size(), N = G[0].size(), seen[40][40][80] = {}, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
        if (K >= M + N - 3) return M + N - 2;
        queue<vector<int>> q;
        q.push({ 0, 0, K, 0 });
        seen[0][0][K] = 1;
        while (q.size()) {
            auto pos = q.front();
            q.pop();
            int x = pos[0], y = pos[1], r = pos[2], val = pos[3];
            for (auto &[dx, dy] : dirs) {
                int a = x + dx, b = y + dy;
                if (a < 0 || b < 0 || a >= M || b >= N) continue;
                int rr = r - (G[x][y] == 1);
                if (rr < 0 || seen[a][b][rr]) continue;
                if (a == M - 1 && b == N - 1) return val + 1;
                seen[a][b][rr] = 1;
                q.push({ a, b, rr, val + 1 });
            }
        }
        return -1;
    }
};

Solution 3. BFS

// OJ: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
// Time: O(MN * min(K, M + N))
// Space: O(MNK)
class Solution {
    int M, N, dp[40][40][80] = {}, dirs[4][2] = { {0,1}, {0,-1},{1,0},{-1,0} }, ans = INT_MAX;
    void dfs(vector<vector<int>> &G, int x, int y, int k, int step) {
        dp[x][y][k] = step;
        if (x == M - 1 && y == N - 1) ans = min(ans, step);
        for (auto [dx, dy] : dirs) {
            int a = x + dx, b = y + dy;
            if (a < 0 || a >= M || b < 0 || b >= N) continue;
            if (k - G[x][y] >= 0 && dp[a][b][k - G[x][y]] > step + 1) dfs(G, a, b, k - G[x][y], step + 1);
        }
    }
public:
    int shortestPath(vector<vector<int>>& G, int k) {
        M = G.size(), N = G[0].size();
        if (k >= M + N - 3) return M + N - 2;
        memset(dp, 0x3f, sizeof(dp));
        for (int i = 0; i < k; ++i) dp[0][0][k] = 0;
        dfs(G, 0, 0, k, 0);
        return ans == INT_MAX ? -1 : ans;
    }
};

Note

  • For shortest path problem, BFS should be the first choice.
  • Initially my solution got TLE just because I didn’t add the check if (K >= M + N - 3) return M + N - 2;. This line reduces the time complexity from O(M^2 * N^2) to O(MN * min(K, M + N)).

Java

  • class Solution {
        public int shortestPath(int[][] grid, int k) {
            if (grid == null || grid.length == 0 || grid[0].length == 0)
                return -1;
            int rows = grid.length, columns = grid[0].length;
            k = Math.max(0, Math.min(k, rows + columns - 3));
            int[][][] distances = new int[rows][columns][k + 1];
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < columns; j++) {
                    for (int e = 0; e <= k; e++)
                        distances[i][j][e] = Integer.MAX_VALUE;
                }
            }
            int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
            distances[0][0][k] = 0;
            Queue<int[]> queue = new LinkedList<int[]>();
            queue.offer(new int[]{0, 0, k});
            while (!queue.isEmpty()) {
                int[] cell = queue.poll();
                int row = cell[0], column = cell[1], remainEliminations = cell[2];
                int distance = distances[row][column][remainEliminations];
                if (row == rows - 1 && column == columns - 1)
                    return distance;
                for (int[] direction : directions) {
                    int newRow = row + direction[0], newColumn = column + direction[1];
                    if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns) {
                        int newRemainEliminations = remainEliminations - grid[newRow][newColumn];
                        if (newRemainEliminations >= 0 && distances[newRow][newColumn][newRemainEliminations] == Integer.MAX_VALUE) {
                            distances[newRow][newColumn][newRemainEliminations] = distance + 1;
                            queue.offer(new int[]{newRow, newColumn, newRemainEliminations});
                        }
                    }
                }
            }
            return -1;
        }
    }
    
  • // OJ: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
    // Time: O(MN * min(K, M + N))
    // Space: O(MN * min(K, M + N))
    class Solution {
    public:
        int shortestPath(vector<vector<int>>& G, int k) {
            int M = G.size(), N = G[0].size(), step = 0, dirs[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
            if (k >= M + N - 3) return M + N - 2;
            bool seen[40][40][80] = {};
            queue<tuple<int, int, int>> q; // x, y, bomb
            q.emplace(0, 0, 0);
            seen[0][0][0] = true;
            while (q.size()) {
                int cnt = q.size();
                while (cnt--) {
                    auto [x, y, bomb] = q.front();
                    q.pop();
                    if (x == M - 1 && y == N - 1) return step;
                    for (auto &[dx, dy] : dirs) {
                        int a = x + dx, b = y + dy;
                        if (a < 0 || a >= M || b < 0 || b >= N) continue;
                        int nextBomb = bomb + G[a][b];
                        if (nextBomb > k || seen[a][b][nextBomb]) continue;
                        q.emplace(a, b, nextBomb);
                        seen[a][b][nextBomb] = true;
                    }
                }
                ++step;
            }
            return -1;
        }
    };
    
  • class Solution:
        def shortestPath(self, grid: List[List[int]], k: int) -> int:
            m, n = len(grid), len(grid[0])
            if k >= m + n - 3:
                return m + n - 2
            q = deque([(0, 0, k)])
            vis = {(0, 0, k)}
            ans = 0
            while q:
                ans += 1
                for _ in range(len(q)):
                    i, j, k = q.popleft()
                    for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
                        x, y = i + a, j + b
                        if 0 <= x < m and 0 <= y < n:
                            if x == m - 1 and y == n - 1:
                                return ans
                            if grid[x][y] == 0 and (x, y, k) not in vis:
                                q.append((x, y, k))
                                vis.add((x, y, k))
                            if grid[x][y] == 1 and k > 0 and (x, y, k - 1) not in vis:
                                q.append((x, y, k - 1))
                                vis.add((x, y, k - 1))
            return -1
    
    
    

All Problems

All Solutions