-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbus-routes.go
68 lines (59 loc) · 1.16 KB
/
bus-routes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
// 815 https://leetcode-cn.com/problems/bus-routes/
// BFS 看注释吧 和 752 909 大同小异
func numBusesToDestination(routes [][]int, source int, target int) int {
// 当前就在了 不用换乘啦
if source == target {
return 0
}
// 记录站点能进入的路线
s2r := make(map[int][]int)
// 经过的路线
q := []int{}
// 进入路线换乘的次数
countMap := make(map[int]int)
for i, r := range routes {
for _, s := range r {
if s == source {
q = append(q, i)
countMap[i] = 1
}
if _, ok := s2r[s]; ok {
s2r[s] = add(s2r[s], i)
} else {
rec := []int{i}
s2r[s] = rec
}
}
}
for len(q) > 0 {
now := q[0]
q = q[1:]
step := countMap[now]
for _, s := range routes[now] {
if s == target {
return step
}
// 将该站点能到的新路线都加入队列
if rs, ok := s2r[s]; ok {
for _, r := range rs {
if _, ok := countMap[r]; !ok {
q = append(q, r)
countMap[r] = step + 1
}
}
}
}
}
return -1
}
// 保证切片元素唯一
func add(s []int, e int) []int {
for _, v := range s {
if v == e {
return s
}
}
s = append(s, e)
return s
}