Advertisement
lifeiteng

815. Bus Routes

Sep 25th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. class Solution {
  2.     public int numBusesToDestination(int[][] routes, int S, int T) {
  3.         Map<Integer, Set<Integer>> buses = new HashMap<>(), route = new HashMap<>();
  4.         int b = 0;
  5.         for(int[] r : routes)
  6.         {
  7.             buses.put(b, new HashSet<>());
  8.             for(int stops : r)
  9.             {
  10.                 buses.get(b).add(stops);
  11.                 if(!route.containsKey(stops)) route.put(stops, new HashSet<>());
  12.                 route.get(stops).add(b);
  13.             }
  14.             b++;
  15.         }
  16.         Queue<Integer> q = new LinkedList<>();
  17.         Set<Integer> set = new HashSet<>();
  18.         // bfs visits, q contains the stops
  19.         q.offer(S);
  20.         int re = 0;
  21.         while(!q.isEmpty())
  22.         {
  23.             int size = q.size();
  24.             for(int i = 0; i < size; i++)
  25.             {
  26.                 int stop = q.poll();
  27.                 if(stop == T) return re;
  28.                 for(int bus : route.get(stop))
  29.                 {
  30.                     if(set.contains(bus)) continue;
  31.                     set.add(bus);
  32.                     for(int next : buses.get(bus))
  33.                         q.offer(next);
  34.                 }
  35.             }
  36.             re++;
  37.         }
  38.         return -1;
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement