[Leetcode] Bus Routes 公交线路
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode] Bus Routes 公交线路
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Bus Routes
詳細(xì)解題思路請(qǐng)?jiān)L問:https://yanjia.me/zh/2018/11/...
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.
代碼
func searchRoute2(routes [][]int, graph map[int]map[int]bool, src, dst int) int {queue := []int{}for routeNum := range graph[src] {queue = append(queue, routeNum)}visited := map[int]bool{}dstRoutes := map[int]bool{}// once one of the route in this map get hit, we find the solutionfor routeNum := range graph[dst] {dstRoutes[routeNum] = true}times := 1// start BFSfor len(queue) != 0 {newQueue := []int{}for _, routeNum := range queue {if _, ok := dstRoutes[routeNum]; ok {return times}for _, stop := range routes[routeNum] {nextRouteNums := graph[stop]for nextRouteNum := range nextRouteNums {// only add route that has been visited before to avoid cycleif _, ok := visited[nextRouteNum]; !ok {newQueue = append(newQueue, nextRouteNum)visited[nextRouteNum] = true}}}}queue = newQueuetimes++}return -1 }// map bus stop number to bus route numbers func buildGraph2(routes [][]int) map[int]map[int]bool {// use a map of map because route could be like 1->2->1->2graph := map[int]map[int]bool{}for i, route := range routes {for _, stop := range route {if _, ok := graph[stop]; ok {graph[stop][i] = true} else {graph[stop] = map[int]bool{i: true,}}}}return graph }func numBusesToDestination(routes [][]int, S int, T int) int {if S == T {return 0}graph := buildGraph2(routes)return searchRoute2(routes, graph, S, T) }總結(jié)
以上是生活随笔為你收集整理的[Leetcode] Bus Routes 公交线路的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大快网站:如何选择正确的hadoop版本
- 下一篇: 传神成进博会唯一指定智能翻译硬件提供商