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 solution
for routeNum := range graph[dst] {
dstRoutes[routeNum] = true
}
times := 1
// start BFS
for 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 cycle
if _, ok := visited[nextRouteNum]; !ok {
newQueue = append(newQueue, nextRouteNum)
visited[nextRouteNum] = true
}
}
}
}
queue = newQueue
times++
}
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->2
graph := 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)
}