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. 20165218 2017-2018-1 《Java程序设计》第一周学习总结

    20165218 2017-2018-1 <Java程序设计>第一周学习总结 教材学习内容总结 第一章.Java入门 1. Java特点 Java具有简单.面向对象.平台无关.多线程.动态 ...

  2. HDOJ(HDU).1035 Robot Motion (DFS)

    HDOJ(HDU).1035 Robot Motion [从零开始DFS(4)] 点我挑战题目 从零开始DFS HDOJ.1342 Lotto [从零开始DFS(0)] - DFS思想与框架/双重DF ...

  3. 浅谈Hibernate框架(一)——.hbm.xml中的配置

    Hibernate一枚“全自动”的ORM框架: 用IDE工具集成Hibernate会自动生成: 以.hbm.xml为后缀结尾的配置文件+ POJO类 + Dao类 主键查询: Session.load ...

  4. props设置state误区

    class Component extends React.Component { constructor(props) { super(props); this.state = { value: t ...

  5. 2067: [Poi2004]SZN——树上贪心+二分

    题目大意: 给一棵树.求用最少的链覆盖这棵树(链不能相交),在这个基础上求最长的链最短可以是多少. n<=10000 题解: 肯定先处理第一问: 答案:$\sum_(du[i]-1)/2+1$ ...

  6. vim 打开中文乱码

    [root@yu ~]# find / -name vimrc/etc/vimrc [root@yu ~]# vim /etc/vimrc set fileencodings=utf-8,gb2312 ...

  7. IntelliJ IDEA 详细图解最常用的配置 ,适合新人,解决eclipse转idea的烦恼

    刚刚使用IntelliJ IDEA 编辑器的时候,会有很多设置,会方便以后的开发,磨刀不误砍柴工. 比如:设置文件字体大小,代码自动完成提示,版本管理,本地代码历史,自动导入包,修改注释,修改tab的 ...

  8. [ZJOI2010]排列计数 (组合计数/dp)

    [ZJOI2010]排列计数 题目描述 称一个1,2,...,N的排列P1,P2...,Pn是Magic的,当且仅当2<=i<=N时,Pi>Pi/2. 计算1,2,...N的排列中有 ...

  9. bzoj 1135 [POI2009]Lyz 线段树+hall定理

    1135: [POI2009]Lyz Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 573  Solved: 280[Submit][Status][ ...

  10. Java的位运算符—与(&)、非(~)、或(|)、异或(^)

    位运算符主要针对二进制,它包括了:“与”.“非”.“或”.“异或”.从表面上看似乎有点像逻辑运算符,但逻辑运算符是针对两个关系运算符来进行逻辑运算,而位运算符主要针对两个二进制数的位进行逻辑运算.下面 ...