funcnumBusesToDestination(routes [][]int, source int, target int)int { n := len(routes) if n == 0 || len(routes[0]) == 0 { return-1 } if source == target { return0 }
g := make(map[int][]int)
for i := 0; i < n; i++ { for _, station := range routes[i] { g[station] = append(g[station], i) } }
type Pair struct { e int k int }
var q []Pair s1 := make(map[int]struct{}) s2 := make(map[int]struct{}) for _, v := range g[source] { if _, o := s2[v]; !o { s2[v] = struct{}{} for _, vv := range routes[v] { if _, ok := s1[vv]; !ok { s1[vv] = struct{}{} q = append(q, Pair{vv, 1}) } } }
}
forlen(q) > 0 { pair := q[0] q = q[1:]
if pair.e == target { return pair.k }
for _, v := range g[pair.e] { if _, o := s2[v]; !o { s2[v] = struct{}{} for _, vv := range routes[v] { if _, ok := s1[vv]; !ok { s1[vv] = struct{}{} q = append(q, Pair{vv, pair.k + 1}) } } }