题目地址:
https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/
给定一个 m m m行 n n n列二维 0 − 1 0-1 0−1矩阵, 0 0 0代表空地, 1 1 1代表障碍物,要求从 ( 0 , 0 ) (0,0) (0,0)出发,走到 ( m − 1 , n − 1 ) (m-1,n-1) (m−1,n−1)这个位置,允许最多移除 k k k个障碍物,求最短路长度。每一步可以上下左右走一步。题目保证出发点和终点都是空地。
思路是BFS。将已经移除了多少个障碍物加进状态,然后做隐式图搜索即可。代码如下:
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;
}
}
时空复杂度 O ( k m n ) O(kmn) O(kmn)。
C++:
class Solution {
public:
struct Node {
int x, y, k;
};
int shortestPath(vector<vector<int>>& g, int k) {
int m = g.size(), n = g[0].size();
if (m == 1 && n == 1) return 0;
int d[] = {-1, 0, 1, 0, -1};
bool vis[m][n][k + 1];
memset(vis, 0, sizeof vis);
queue<Node> q;
q.push({0, 0, k});
vis[0][0][k] = true;
int step = 0;
while (q.size()) {
step++;
for (int i = q.size(); i; i--) {
auto t = q.front(); q.pop();
int x = t.x, y = t.y, k = t.k;
for (int j = 0; j < 4; j++) {
int nx = x + d[j], ny = y + d[j + 1];
if (0 <= nx && nx < m && 0 <= ny && ny < n) {
if (!g[nx][ny] && !vis[nx][ny][k]) {
if (nx == m - 1 && ny == n - 1) return step;
q.push({nx, ny, k});
vis[nx][ny][k] = true;
}
if (g[nx][ny] && k && !vis[nx][ny][k - 1]) {
if (nx == m - 1 && ny == n - 1) return step;
q.push({nx, ny, k - 1});
vis[nx][ny][k - 1] = true;
}
}
}
}
}
return -1;
}
};
时空复杂度一样。