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. HDOJ(HDU).1258 Sum It Up (DFS)

    HDOJ(HDU).1258 Sum It Up (DFS) [从零开始DFS(6)] 点我挑战题目 从零开始DFS HDOJ.1342 Lotto [从零开始DFS(0)] - DFS思想与框架/双 ...

  2. 从零开始学Linux系统(四)之Vi/Vim操作指令

    模式切换: 编辑模式 <-- [:]<--命令模式 -->[a.i.o A.I.O]-->  插入模式 编辑模式操作: 设置行号  :set nu   :set nonu 复制 ...

  3. bzoj1854: [Scoi2010]游戏(匈牙利) / GDKOI Day2 T2(最大流)

    题目大意:有n(<=1000000)个装备,每个装备有两个属性值(<=10000),每个装备只能用一次,使用某一个值,攻击boss必须先使用属性为1的,再使用属性为2的,再使用属性为3的, ...

  4. 【简单算法】40.Fizz Buzz

    题目: 写一个程序,输出从 到 n 数字的字符串表示. . 如果 n 是3的倍数,输出“Fizz”: . 如果 n 是5的倍数,输出“Buzz”: .如果 n 同时是3和5的倍数,输出 “FizzBu ...

  5. 《时间序列分析及应用:R语言》读书笔记--第一章 引论

    "春节假期是难得的读书充电的时间."--来自某boss.假期能写多少算多少,一个是题目中的这本书,另一个是<python核心编程>中的高级部分,再一个是拖着的<算 ...

  6. java中new一个对象放在循环体里面与外面的区别

    首先说下问题: 这次在做项目的是出现了一个new对象在循环里面与外面造成的不同影响. 大家可以看到这个new的对象放在不同的位置产生的效果是不一样的. 经过多方查询与验证可以得出结论: * EasyU ...

  7. MongoDB入门(2)- MongoDB安装

    windows安装 下载文件,解压缩即可.下载地址 每次运行mongod --dbpath D:/MongoDB/data 命令行来启动MongoDB实在是不方便,把它作为Windows服务,这样就方 ...

  8. Linux修改用户密码

    1. root修改自己 # passwd 2. root修改别人 # passwd oracle //修改oracle的密码

  9. mysql数据库cmd直接登录

    找到mysql的安装路径: 将该路径配置到环境变量中: win+R代开dos窗口:输入mysql -uroot -p回车,输入密码.

  10. CPU上下文切换的次数和时间(context switch)

    什么是CPU上下文切换? 现在linux是大多基于抢占式,CPU给每个任务一定的服务时间,当时间片轮转的时候,需要把当前状态保存下来,同时加载下一个任务,这个过程叫做上下文切换.时间片轮转的方式,使得 ...