August 14, 2022

1293. Shortest Path in a Grid with Obstacles Elimination

1293. Shortest Path in a Grid with Obstacles Elimination

BFS. Time = O(MNK), space = O(MNK)

class Solution {
    public int shortestPath(int[][] grid, int k) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0, k});
        int[][] dirs = `{`{-1, 0}, {1, 0}, {0, -1}, {0, 1}`}`;
        int steps = 0;
        boolean[][][] visited = new boolean[grid.length][grid[0].length][k + 1];
        visited[0][0][0] = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                if (cur[0] == grid.length - 1 && cur[1] == grid[0].length - 1) {
                    return steps;
                }
                for (int[] dir : dirs) {
                    int row = cur[0] + dir[0];
                    int col = cur[1] + dir[1];
                    int newK = cur[2];
                    if (row >= 0 && col >= 0 && row < grid.length && col < grid[0].length) {
                         
                        if (grid[row][col] == 1) {
                            newK -= 1;
                        } 
                        
                        if (newK >= 0 && !visited[row][col][newK]) {
                            queue.offer(new int[]{row, col, newK});
                            visited[row][col][newK] = true;
                        }
                        
                    }
                }
            }
            steps ++;
        }
        return -1;
    }
}
comments powered by Disqus