欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

[Leetcode] Bus Routes 公交线路

发布时间:2024/9/21 编程问答 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [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 公交线路的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。