Q15 Bus Routes - LeetCode 815

PHOTO EMBED

Mon Apr 24 2023 03:19:44 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    public int numBusesToDestination(int[][] routes, int source, int target) {
       /* Q8 graph playlist , make a hashmap of busstops - busses , busvisited , 
       busStop visited . first add all busStops -> busses in hashmap 
       
       add source bus to q and fire bfs with a level variable in 2 while loops
       
       take out bus from busstops in HM and add all busStops which can be reached from that
       busStop , as they can all reach with 1 bus only , mark bus and bus stop visited and 
       increase level 

       return level when target busStop is reachedd
       */

       //making a HM of busstops -> busno.
       HashMap<Integer,ArrayList<Integer>> map = new HashMap<>();

       //adding bustops -> busno.
       for(int i =0 ; i< routes.length ; i++){
           for(int j = 0 ; j < routes[i].length ; j++){
               ArrayList<Integer> temp = map.getOrDefault(routes[i][j] , new ArrayList<>());
               temp.add(i);
               map.put(routes[i][j] , temp);
           }
       }

       LinkedList<Integer> q = new LinkedList<>();
       HashSet<Integer> busVisited = new HashSet<>();
       HashSet<Integer> busStopVisited = new HashSet<>();
       int level = 0;

        //adding source busStop to Q
        q.addLast(source);

        while(q.size() > 0){
            int size = q.size();

            while(size-- > 0){
                //getting busses corresponding to bus stop
                int rem = q.pop();
                if(rem == target)
                return level;

                ArrayList<Integer> busses = map.get(rem);

                //looping over all the busses which can be taken from the current busStop
                for(int bus : busses){
                    
                    //only if the bus is not visited
                    if(busVisited.contains(bus) == false){
                        int [] busStops = routes[bus];
                        
                        //getting busStops which can be reached for current bus
                        for(int busStoops : busStops){
                            
                            //only if the busStop is not visited
                            if(busStopVisited.contains(busStoops) == false){
                                q.addLast(busStoops);
                                busStopVisited.add(busStoops);  //marking visited
                            }
                        }
                        busVisited.add(bus);    //marking visited
                    }
                }
                
            }
            level++;
        }

        return - 1;
       
    }
}









content_copyCOPY

https://leetcode.com/problems/bus-routes/