We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.

We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.

Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output: 2
Explanation:
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.

Note:

  • 1 <= routes.length <= 500.
  • 1 <= routes[i].length <= 500.
  • 0 <= routes[i][j] < 10 ^ 6.

分析:有点类似于求最短路径,那么马上联想到图的BFS的DFS。因为求的是最短所以优先采用BFS。对于每个bus route,因为他是循环发车的,即从头能到尾,所以一条线上的站肯定是互通的。遍历所有bus route,得到每个站在哪些route上,如果两个站所在的route相同则一定可达。再从起始点S出发,找到所有与其处在相同route上的station,如果有目标站T则停止遍历,否则继续以这些station为开始点继续广度遍历。

class Solution {
public int numBusesToDestination(int[][] routes, int S, int T) {
HashSet<Integer> visited = new HashSet<>();  // 访问标记,防止BFS时重复遍历
Queue<Integer> q = new LinkedList<>();  // BFS借助队列实现,DFS借助栈来实现
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();  // station——station所在的所有route
int ret = 0; if (S==T) return 0;

    // 统计每个station和其所对在的bus route
for(int i = 0; i < routes.length; i++){
for(int j = 0; j < routes[i].length; j++){
ArrayList<Integer> buses = map.getOrDefault(routes[i][j], new ArrayList<>());
buses.add(i);
map.put(routes[i][j], buses);
}
} q.offer(S); // 从初始站开始遍历
while (!q.isEmpty()) {
int len = q.size();
ret++;
for (int i = 0; i < len; i++) {
int cur = q.poll();
ArrayList<Integer> buses = map.get(cur);
for (int bus: buses) {
if (visited.contains(bus)) continue;
visited.add(bus);
for (int j = 0; j < routes[bus].length; j++) {
if (routes[bus][j] == T) return ret;
q.offer(routes[bus][j]);
}
}
}
}
return -1;
}
}

LeetCode解题报告—— Bus Routes的更多相关文章

  1. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  2. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  3. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  4. 【leetcode】815. Bus Routes

    题目如下: We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. ...

  5. leetCode解题报告5道题(六)

    题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...

  6. LeetCode解题报告—— Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  7. LeetCode解题报告—— Search in Rotated Sorted Array & Search for a Range & Valid Sudoku

    1. Search in Rotated Sorted Array Suppose an array sorted in ascending order is rotated(轮流,循环) at so ...

  8. LeetCode解题报告—— 2 Keys Keyboard & Longest Palindromic Substring & ZigZag Conversion

    1. Longest Palindromic Substring Given a string s, find the longest palindromic substring in s. You ...

  9. LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum

    1. 1-bit and 2-bit Characters We have two special characters. The first character can be represented ...

随机推荐

  1. (ex)BSGS题表

    学了一下BSGS大概知道他是什么了,但是并没有做什么难题,所以也就会个板子.普通的BSGS,我还是比较理解的,然而exBSGS我却只理解个大概,也许还会个板子......(这个东西好像都会有一群恶心的 ...

  2. c++ linux 判断string是中文的 or 英文的 字符串。

    #include <iostream> #include <string.h> #include <stdio.h> #include <stdlib.h&g ...

  3. MyEclipse下项目的包层次结构调整

    新电脑安装完MyEclipse,导入项目后发现MyEclipse下项目的包层次结构变成了Flat,平面模式,这种模式感觉特别不好, 不能清晰地显示出项目的包层次结构.这样,显示出的包的结构不够明显,我 ...

  4. udhcpd源码分析4--获取client报文及发包动作

    1:重要的结构体 获取的报文是UDP的payload部分,结构体struct dhcpMessage描述了dhcp报文的结构. /* packet.h */ struct dhcpMessage { ...

  5. c# 折半查找法实现代码

    ] { , , , , , , , , , , , , , , , , , , , }; , i; string j, k; , ); ) { k = String.Format("未找到{ ...

  6. java mysql 连接

    第一种: //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名mydata String url = & ...

  7. flask-login源码梳理

  8. mysql 数据库备份与还原,用户的创建与删除,用户的密码修改

    1.备份数据库 要退出mysql rimideiMac-23:~ rimi$    mysqldump -u root -p pro >pro.sql ls 查看路径 2.恢复数据库 2.1直接 ...

  9. [uva11137]立方数之和·简单dp

    小水题再来一发 给定一个正整数n<=1e4,求将n写成若干个正整数立方和的方法数 典型的多阶段模型 f[i][j]表示当前用到1~i的数,累计和为j的方案数. #include<cstdi ...

  10. 【BZOJ4818】【SDOI2017】序列计数 [矩阵乘法][DP]

    序列计数 Time Limit: 30 Sec  Memory Limit: 128 MB[Submit][Status][Discuss] Description Alice想要得到一个长度为n的序 ...