815. 公交路线
给你一个数组 routes ,表示一系列公交线路,其中每个 routes[i] 表示一条公交线路,第 i 辆公交车将会在上面循环行驶。
- 例如,路线 routes[0] = [1, 5, 7] 表示第 0 辆公交车会一直按序列 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> … 这样的车站路线行驶。
现在从 source 车站出发(初始时不在公交车上),要前往 target 车站。 期间仅可乘坐公交车。
求出 最少乘坐的公交车数量 。如果不可能到达终点车站,返回 -1 。
示例 1:
输入:routes = [[1,2,7],[3,6,7]], source = 1, target = 6 输出:2 解释:最优策略是先乘坐第一辆公交车到达车站 7 , 然后换乘第二辆公交车到车站 6 。
示例 2:
输入:routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12 输出:-1
提示:
- 1 <= routes.length <= 500.
- 1 <= routes[i].length <= 105
- routes[i] 中的所有值 互不相同
- sum(routes[i].length) <= 105
- 0 <= routes[i][j] < 106
- 0 <= source, target < 106
思路:
如何建图?
考虑将每条公交路线看作一个点
即找从所有包含源点公交站的公交路线到所有包含终点公交站的所有公交路线的最短距离
只要任意两条路线有相同的公交站,说明相互可达。
class Solution {public int numBusesToDestination(int[][] routes, int source, int target) {int n = routes.length;if (source == target) return 0;boolean[][] st = new boolean[n][n];Map<Integer, List<Integer>> map = new HashMap<>();for (int i = 0; i < n; i++) {for (int x : routes[i]) {List<Integer> t = map.getOrDefault(x, new ArrayList<>());for (int j : t) {st[i][j] = st[j][i] = true;}t.add(i);map.put(x, t);}}int[] d = new int[n];Arrays.fill(d, 0x3f3f3f3f);Queue<Integer> q = new LinkedList<>();for (int x : map.get(source)) {d[x] = 1;q.offer(x);}while (!q.isEmpty()) {int u = q.poll();for (int i = 0; i < n; i++) {if (i == u) continue;if (st[i][u] && d[i] > d[u] + 1) {d[i] = d[u] + 1;q.offer(i);}}}int min = 0x3f3f3f3f;for (int x : map.getOrDefault(target, new ArrayList<>()))min = Math.min(min, d[x]);return min == 0x3f3f3f3f ? -1: min;}}
Acwing 3675. 逃离迷宫

思路:本质是单源最短路问题
不同点在于可将每条长或宽看作一个点,每条边为拐弯一次。
import java.util.*;public class Main {static final int INF = 0x3f3f3f3f, N = 110;static int n, m;static char[][] c = new char[N][];static int[][] res = new int[N][N];static int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};static boolean[][] st = new boolean[N][N];public static void main(String[] args) {Scanner sc = new Scanner(System.in);int T = sc.nextInt();while (T-- > 0) {n = sc.nextInt();m = sc.nextInt();for (int i = 1; i <= n; i++)c[i] = (" " + sc.next()).toCharArray();for (int i = 1; i <= n; i++) {Arrays.fill(res[i], 1, m + 1, INF);Arrays.fill(st[i], 1, m + 1, false);}int k = sc.nextInt();int sx, sy, ex, ey;sy = sc.nextInt();sx = sc.nextInt();ey = sc.nextInt();ex = sc.nextInt();res[sx][sy] = -1;Queue<int[]> q = new LinkedList<>();q.offer(new int[]{sx, sy, -1});st[sx][sy] = true;while (!q.isEmpty()) {int[] p = q.poll();int x = p[0], y = p[1], t = p[2];for (int i = 0; i < 4; i++) {int a = x + dx[i], b = y + dy[i];while (a >= 1 && a <= n && b >= 1 && b <= m && c[a][b] == '.') {if (!st[a][b]) {res[a][b] = t + 1;st[a][b] = true;q.offer(new int[]{a, b, t + 1});}a = a + dx[i];b = b + dy[i];}}}// for (int i = 1; i <= n; i++) {// for (int j = 1; j <= m; j++) {// System.out.printf("%-10d ", res[i][j]);// }// System.out.println();// }// System.out.println(res[ex][ey] + " " + k);if (res[ex][ey] <= k)System.out.println("yes");else System.out.println("no");}}}
