Rutas de autobuses

Tenemos una lista de rutas de autobuses. Cada  routes[i] una es una ruta de autobús que el i-ésimo autobús repite para siempre. Por ejemplo routes[0] = [1, 5, 7], si  , esto significa que el primer bus (0º indexado) viaja en la secuencia 1-> 5-> 7-> 1-> 5-> 7-> 1 -> ... para siempre.

Comenzamos en la parada de autobús  S (inicialmente no en un autobús), y queremos ir a la parada de autobús  T. Viajando solo en autobuses, ¿cuál es la menor cantidad de autobuses que debemos tomar para llegar a nuestro destino? Devuelve -1 si no es posible.

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.

Idea: El significado de esta pregunta es: la misma línea de autobús solo se cuenta como un tren, que es solo un paso, luego la siguiente capa es recoger todas las estaciones de la estación principal;

Tiempo: O (V + E); Espacio: O (V);

Nota: 1. El mismo bus solo necesita sentarse una vez, por lo tanto, el visitado contiene bus, no estación;

            2. La misma línea pertenece al mismo bus, solo se cuenta una vez, así que coloque toda la misma línea en la siguiente capa;

class Solution {
    public int numBusesToDestination(int[][] routes, int S, int T) {
        if(routes == null || routes.length == 0 || routes[0].length == 0) {
            return -1;
        }
        HashMap<Integer, HashSet<Integer>> graph = new HashMap<>();
        for(int i = 0; i < routes.length; i++) {
            for(int j = 0; j < routes[i].length; j++) {
                int bus = i;
                int station = routes[i][j];
                graph.putIfAbsent(station, new HashSet<Integer>());
                graph.get(station).add(bus);
            }
        }
        
        Queue<Integer> queue = new LinkedList<Integer>();
        HashSet<Integer> visited = new HashSet<Integer>();
        queue.offer(S);
        int step = 0;
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                Integer head = queue.poll();
                if(head == T) {
                    return step;
                }
                for(Integer bus: graph.get(head)) {
                    // 同一个bus只需要坐一次;所以visited里面包含的是bus,不是station;
                    if(!visited.contains(bus)) {
                        visited.add(bus);
                    // 同一个线路,属于同一个bus,只算一次;所以把同一个线路的全部放到下一层;
                        for(int j = 0; j < routes[bus].length; j++) {
                              queue.offer(routes[bus][j]);
                        }
                    }
                }
            }
            step++;
        }
        return -1;
    }
}

 

710 artículos originales publicados · Me gusta 13 · Visitas 190,000+

Supongo que te gusta

Origin blog.csdn.net/u013325815/article/details/105309580
Recomendado
Clasificación