Problem solution · Java

Time to Cross a Bridge

Time to Cross a Bridge: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
68 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeTime to Cross a Bridge · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int findCrossingTime(int n, int k, int[][] time) {    int ans = 0;    // (leftToRight + rightToLeft, i)    Queue<Pair<Integer, Integer>> leftBridgeQueue = createMaxHeap();    Queue<Pair<Integer, Integer>> rightBridgeQueue = createMaxHeap();    // (time to be idle, i)    Queue<Pair<Integer, Integer>> leftWorkers = createMinHeap();    Queue<Pair<Integer, Integer>> rightWorkers = createMinHeap();     for (int i = 0; i < k; ++i)      leftBridgeQueue.offer(new Pair<>(          /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i));     while (n > 0 || !rightBridgeQueue.isEmpty() || !rightWorkers.isEmpty()) {      // Idle left workers get on the left bridge.      while (!leftWorkers.isEmpty() && leftWorkers.peek().getKey() <= ans) {        final int i = leftWorkers.poll().getValue();        leftBridgeQueue.offer(new Pair<>(            /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i));      }      // Idle right workers get on the right bridge.      while (!rightWorkers.isEmpty() && rightWorkers.peek().getKey() <= ans) {        final int i = rightWorkers.poll().getValue();        rightBridgeQueue.offer(new Pair<>(            /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i));      }       if (!rightBridgeQueue.isEmpty()) {        // If the bridge is free, the worker waiting on the right side of the        // bridge gets to cross the bridge. If more than one worker is waiting        // on the right side, the one with the lowest efficiency crosses first.        final int i = rightBridgeQueue.poll().getValue();        ans += /*rightToLeft*/ time[i][2];        leftWorkers.offer(new Pair<>(ans + /*putNew*/ time[i][3], i));      } else if (!leftBridgeQueue.isEmpty() && n > 0) {        // If the bridge is free and no worker is waiting on the right side, and        // at least one box remains at the old warehouse, the worker on the left        // side of the river gets to cross the bridge. If more than one worker        // is waiting on the left side, the one with the lowest efficiency        // crosses first.        final int i = leftBridgeQueue.poll().getValue();        ans += /*leftToRight*/ time[i][0];        rightWorkers.offer(new Pair<>(ans + /*pickOld*/ time[i][1], i));        --n;      } else {        // Advance the time of the last crossing worker.        ans = Math.min(!leftWorkers.isEmpty() && n > 0 ? leftWorkers.peek().getKey()                                                       : Integer.MAX_VALUE,                       !rightWorkers.isEmpty() ? rightWorkers.peek().getKey() : Integer.MAX_VALUE);      }    }     return ans;  }   private Queue<Pair<Integer, Integer>> createMaxHeap() {    return new PriorityQueue<>(        Comparator.comparing(Pair<Integer, Integer>::getKey, Comparator.reverseOrder())            .thenComparing(Pair<Integer, Integer>::getValue, Comparator.reverseOrder()));  }   private Queue<Pair<Integer, Integer>> createMinHeap() {    return new PriorityQueue<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey)                                   .thenComparingInt(Pair<Integer, Integer>::getValue));  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗