815. Bus Routes
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.
https://www.youtube.com/watch?v=vEcm5farBls
Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output: 2
[[1, : 0
2, : 0
7],: 0, 1
[3, : 1
6, : 1
class Solution { public int numBusesToDestination(int[][] routes, int S, int T) { if(S == T) return 0; HashMap<Integer, List<Integer>> map = new HashMap<>(); // fill in the map, key: stop id, value : bus id for(int i = 0; i < routes.length; i++){ for(int j = 0; j < routes[i].length; j++){ // try get or default . if map.getKey(routes[i][j]) is null, then return new ArrayList<>(); // if map.getKey(routes[i][j]) is not null, then return map.getKey(routes[i][j]) List<Integer> buses = map.getOrDefault(routes[i][j], new ArrayList<>()); // buses if the list of the buses that stop at this stop buses.add(i); map.put(routes[i][j], buses); } } // after done filling up the map, we want to start from the start pos, and get all the stops which are at the // same level as start pos, see if there is destination among those, if yes, then the number of bus we used is just 1 // otherwise, we put all of them into the queue and expand // if after queue is empty and we haven't returned anything , then no path exists , return -1 // use an int level to represent how many buses we used so far, the level // use a set visited to mark the visited bus as visited, so we don't come back to count it again to // guarentee the minimum number HashSet<Integer> visited = new HashSet<>(); int level = 0; Queue<Integer> queue = new LinkedList<>(); queue.offer(S); while(!queue.isEmpty()){ int size = queue.size(); level++; for(int i = 0; i < size; i++){ int cur = queue.poll(); // 1 // get all the bus that stop at 1, and then get all the stop same level as 1 List<Integer> buses = map.get(cur); // buses = [0] // get all the stops same level as 1 for(int bus : buses){ //List<Integer> stops = routes[bus]; if(visited.contains(bus)) continue; visited.add(bus); for(int stop : routes[bus]){ if(stop == T){ return level; }else{ queue.offer(stop); } } } } } return -1; } }
posted on 2018-08-30 03:28 猪猪🐷 阅读(144) 评论(0) 收藏 举报
浙公网安备 33010602011771号