日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[Leetcode] Bus Routes 公交线路

發布時間:2024/9/21 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Leetcode] Bus Routes 公交线路 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Bus Routes

詳細解題思路請訪問: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) }

總結

以上是生活随笔為你收集整理的[Leetcode] Bus Routes 公交线路的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。