原题链接在这里:https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
题目:
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
题解:
Use BFS to track the shortest path. In queue, we need coordinate and current count of obstacles eliminated.
For the polled coordinate, if it is the lower right corner, then return the BFS level as step.
Otherwise, check 4 directions, if the new position is wihtin boundary, and new obstacle count <= k, and previous visited obstacle count is > new obstacle count. Add it to the que. And mark visited as current obstacle count.
Time Complexity: O(m * n * k). As for the worst case, each cell is put in and out of queue totally k times.
Space: O(m * n * k).
AC Java:
1 class Solution { 2 public int shortestPath(int[][] grid, int k) { 3 if(grid == null || grid.length == 0 || grid[0].length == 0){ 4 return -1; 5 } 6 7 int m = grid.length; 8 int n = grid[0].length; 9 10 int [][] visited = new int[m][n]; 11 for(int [] arr : visited){ 12 Arrays.fill(arr, Integer.MAX_VALUE); 13 } 14 15 int level = 0; 16 LinkedList<int []> que = new LinkedList<>(); 17 if(grid[0][0] == 0){ 18 que.add(new int[]{0, 0, 0}); 19 visited[0][0] = 0; 20 }else{ 21 if(k < 1){ 22 return -1; 23 } 24 25 que.add(new int[]{0, 0 ,1}); 26 visited[0][0] = 1; 27 } 28 29 int [][] dirs = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; 30 31 while(!que.isEmpty()){ 32 int size = que.size(); 33 while(size-- > 0){ 34 int [] cur = que.poll(); 35 if(cur[0] == m - 1 && cur[1] == n - 1){ 36 return level; 37 } 38 39 for(int [] dir : dirs){ 40 int x = cur[0] + dir[0]; 41 int y = cur[1] + dir[1]; 42 if(x < 0 || x >= m || y < 0 || y >= n){ 43 continue; 44 } 45 46 int step = grid[x][y] + cur[2]; 47 if(step > k || visited[x][y] <= step){ 48 continue; 49 } 50 51 que.add(new int[]{x, y, step}); 52 visited[x][y] = step; 53 } 54 } 55 56 level++; 57 } 58 59 return -1; 60 } 61 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12440920.html