LeetCode 815. Bus Routes(java)

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.

Graph + BFS, 問題在於怎麼構圖。不要用複雜的方法構圖,就用原本就有的關係。一個站點對應哪些bus, queue裏存放站點,然後每次bfs就是找此站點對應的所有一層的bus,把所有bus能到的站點(未訪問過的)都放進queue。
class Solution {
    public int numBusesToDestination(int[][] routes, int S, int T) {
       if (S==T) return 0; 
       HashSet<Integer> visited = new HashSet<>();
       Queue<Integer> q = new LinkedList<>();
       HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
       int res = 0; 
       for(int i = 0; i < routes.length; i++){
            for(int j = 0; j < routes[i].length; j++){   
                if (!map.containsKey(routes[i][j])) map.put(routes[i][j], new ArrayList<>());
                map.get(routes[i][j]).add(i);
            }       
        }
       q.offer(S); 
       while (!q.isEmpty()) {
           int len = q.size();
           res++;
           for (int i = 0; i < len; i++) {
               int cur = q.poll();
               ArrayList<Integer> buses = map.get(cur);
               for (int bus: buses) {
                    if (visited.contains(bus)) continue;
                    visited.add(bus);
                    for (int j = 0; j < routes[bus].length; j++) {
                        if (routes[bus][j] == T) return res;
                        q.offer(routes[bus][j]);  
                   }
               }
           }
        }
        return -1;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章