题目地址:
https://leetcode.com/problems/shortest-path-to-get-food/
给定一个
m
m
m行
n
n
n列的二维矩阵,其中只含四个符号*
,#
,O
,X
,分别代表起点,终点(起点唯一,但终点不唯一),空地和障碍物。每一步可以走四个方向,不能走到障碍物上。问从起点出发最少走多少步可以走到任意一个终点。
思路是双向BFS。从两个方向同时搜即可。代码如下:
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int getFood(char[][] grid) {
int m = grid.length, n = grid[0].length;
Queue<int[]> beginQueue = new LinkedList<>(), endQueue = new LinkedList<>();
boolean[][] beginVisited = new boolean[m][n], endVisited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '*') {
beginQueue.offer(new int[]{i, j});
beginVisited[i][j] = true;
} else if (grid[i][j] == '#') {
endQueue.offer(new int[]{i, j});
endVisited[i][j] = true;
}
}
}
int res = 0;
while (!beginQueue.isEmpty() && !endQueue.isEmpty()) {
// 从起点往终点走一步
res++;
if (oneStep(beginQueue, beginVisited, endVisited, grid)) {
return res;
}
// 从终点往起点走一步,注意这里的函数参数要变换一下
res++;
if (oneStep(endQueue, endVisited, beginVisited, grid)) {
return res;
}
}
return -1;
}
// 返回从起点是否走到了终点的范围
private boolean oneStep(Queue<int[]> beginQueue, boolean[][] beginVisited, boolean[][] endVisited, char[][] grid) {
int[] d = {1, 0, -1, 0, 1};
int size = beginQueue.size();
for (int i = 0; i < size; i++) {
int[] cur = beginQueue.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) && !beginVisited[nextX][nextY] && grid[nextX][nextY] != 'X') {
if (endVisited[nextX][nextY]) {
return true;
}
beginVisited[nextX][nextY] = true;
beginQueue.offer(new int[]{nextX, nextY});
}
}
}
return false;
}
private boolean inBound(int x, int y, char[][] grid) {
return 0 <= x && x < grid.length && 0 <= y && y < grid[0].length;
}
}
时空复杂度 O ( m n ) O(mn) O(mn)。