Saturday, December 8, 2018

[LINT] 825. Bus Station

Version #1 Classical BFS
key is how to get next buses
-> We can get the next bus from the current bus if any stop in route[curr] also contains that next bus
65.24%
public int getMinTransferNumber(int N, int[][] route, int A, int B) {
        // Write your code here
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i < N; i++) {
            for (int r = 0; r < route[i].length; r++) {
                map.putIfAbsent(route[i][r], new HashSet<>());
                map.get(route[i][r]).add(i);
            }
        }
        Queue<Integer> que = new LinkedList<>();
        for (int initBus : map.get(A)) {
            que.offer(initBus);
        }
        map.remove(A);
        int step = 0;
        while (!que.isEmpty() && !map.isEmpty()) {
            step++;
            int size = que.size();
            while (size-- > 0) {
                int currBus = que.poll();
                for (int stop : route[currBus]) { // stops that can be reached from
                    if (stop == B) {
                        return step;
                    }
                    if (map.containsKey(stop)) {
                        Set<Integer> buses = map.get(stop);
                        for (int bus : buses) {
                            que.offer(bus);
                        }
                        map.remove(stop);
                    }
                }
            }
        }
        return -1;
    }

No comments:

Post a Comment