【Leetcode】1293. Shortest Path in a Grid with Obstacles Elimination

Subject address:

https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/

Given a mmm linennn columns two-dimensional0 − 1 0-101 matrix,0 00 means open space,1 11 represents an obstacle, and the requirement is from(0, 0) (0,0)(0,0 ) , go to(m − 1, n − 1) (m-1,n-1)(m1,n1 ) This position allows up tokk tobe removedFor k obstacles, find the shortest path length. Each step can be one step up, down, left and right. The title guarantees that both the starting point and the ending point are open spaces.

The idea is BFS. Add how many obstacles have been removed to the state, and then do an implicit graph search. code show as below:

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    
    
    public int shortestPath(int[][] grid, int k) {
    
    
        if (grid.length <= 1 && grid[0].length <= 1) {
    
    
            return 0;
        }
        
        // 前两个数代表坐标,最后一个数代表已经移除了多少个障碍物
        int[] start = {
    
    0, 0, 0};
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(start);
        boolean[][][] visited = new boolean[grid.length][grid[0].length][k + 1];
        visited[0][0][0] = true;
        
        int[] d = {
    
    1, 0, -1, 0, 1};
        
        int res = 0;
        while (!queue.isEmpty()) {
    
    
            res++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
    
    
                int[] cur = queue.poll();
                for (int j = 0; j < 4; j++) {
    
    
                    int nextX = cur[0] + d[j], nextY = cur[1] + d[j + 1];
                    if (inBound(nextX, nextY, grid)) {
    
    
                        int obs = cur[2] + grid[nextX][nextY];
                        int[] next = {
    
    nextX, nextY, obs};
                        if (obs <= k && !visited[nextX][nextY][obs]) {
    
    
                            if (nextX == grid.length - 1 && nextY == grid[0].length - 1) {
    
    
                                return res;
                            }
                            
                            queue.offer(next);
                            visited[nextX][nextY][obs] = true;
                        }
                    }
                }
            }
        }
        
        return -1;
    }
    
    private boolean inBound(int x, int y, int[][] grid) {
    
    
        return 0 <= x && x < grid.length && 0 <= y && y < grid[0].length;
    }
}

Time and space complexity O (kmn) O(kmn)O ( k m n )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/112765550