Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int numBusesToDestination(int[][] routes, int S, int T) {
- Map<Integer, Set<Integer>> buses = new HashMap<>(), route = new HashMap<>();
- int b = 0;
- for(int[] r : routes)
- {
- buses.put(b, new HashSet<>());
- for(int stops : r)
- {
- buses.get(b).add(stops);
- if(!route.containsKey(stops)) route.put(stops, new HashSet<>());
- route.get(stops).add(b);
- }
- b++;
- }
- Queue<Integer> q = new LinkedList<>();
- Set<Integer> set = new HashSet<>();
- // bfs visits, q contains the stops
- q.offer(S);
- int re = 0;
- while(!q.isEmpty())
- {
- int size = q.size();
- for(int i = 0; i < size; i++)
- {
- int stop = q.poll();
- if(stop == T) return re;
- for(int bus : route.get(stop))
- {
- if(set.contains(bus)) continue;
- set.add(bus);
- for(int next : buses.get(bus))
- q.offer(next);
- }
- }
- re++;
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement