Approach
Breadth-first search
For Time to Cross a Bridge, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 68 lines of Java from the credited upstream file 2532.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int findCrossingTime(int n, int k, int[][] time) {3 int ans = 0;4 5 Queue<Pair<Integer, Integer>> leftBridgeQueue = createMaxHeap();6 Queue<Pair<Integer, Integer>> rightBridgeQueue = createMaxHeap();7 8 Queue<Pair<Integer, Integer>> leftWorkers = createMinHeap();9 Queue<Pair<Integer, Integer>> rightWorkers = createMinHeap();10 11 for (int i = 0; i < k; ++i)12 leftBridgeQueue.offer(new Pair<>(13 time[i][0] + time[i][2], i));14 15 while (n > 0 || !rightBridgeQueue.isEmpty() || !rightWorkers.isEmpty()) {16 17 while (!leftWorkers.isEmpty() && leftWorkers.peek().getKey() <= ans) {18 final int i = leftWorkers.poll().getValue();19 leftBridgeQueue.offer(new Pair<>(20 time[i][0] + time[i][2], i));21 }22 23 while (!rightWorkers.isEmpty() && rightWorkers.peek().getKey() <= ans) {24 final int i = rightWorkers.poll().getValue();25 rightBridgeQueue.offer(new Pair<>(26 time[i][0] + time[i][2], i));27 }28 29 if (!rightBridgeQueue.isEmpty()) {30 31 32 33 final int i = rightBridgeQueue.poll().getValue();34 ans += time[i][2];35 leftWorkers.offer(new Pair<>(ans + time[i][3], i));36 } else if (!leftBridgeQueue.isEmpty() && n > 0) {37 38 39 40 41 42 final int i = leftBridgeQueue.poll().getValue();43 ans += time[i][0];44 rightWorkers.offer(new Pair<>(ans + time[i][1], i));45 --n;46 } else {47 48 ans = Math.min(!leftWorkers.isEmpty() && n > 0 ? leftWorkers.peek().getKey()49 : Integer.MAX_VALUE,50 !rightWorkers.isEmpty() ? rightWorkers.peek().getKey() : Integer.MAX_VALUE);51 }52 }53 54 return ans;55 }56 57 private Queue<Pair<Integer, Integer>> createMaxHeap() {58 return new PriorityQueue<>(59 Comparator.comparing(Pair<Integer, Integer>::getKey, Comparator.reverseOrder())60 .thenComparing(Pair<Integer, Integer>::getValue, Comparator.reverseOrder()));61 }62 63 private Queue<Pair<Integer, Integer>> createMinHeap() {64 return new PriorityQueue<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey)65 .thenComparingInt(Pair<Integer, Integer>::getValue));66 }67}68