Harbor Ferry Route Planner
The Seaport dispatch team manages a fleet of ferries traveling between docks (0 to n-1). Due to heavy traffic or maintenance, certain route checkpoints are Suspended. Your mission in Harbor Ferry Route Planner is to find the Shortest Path (minimum number of docks) from an origin dock to a target dock while avoiding all suspended stations.
The "secret sauce" here is Breadth-First Search (BFS). Since each ferry hop counts as one unit of distance, BFS is the perfect algorithm to find the quickest route. You explore dock by dock, starting from the source, while skipping any path that hits a suspended dock. If a route exists, return the total count of docks in that path; if the destination is cut off, return `-1`. This planning tool is vital for keeping the harbor transit running smoothly during harbor emergencies or scheduled maintenance. It’s a classic shortest-path challenge that teaches you how to navigate networks with dynamic barriers efficiently!
When the task involves connectivity or route cost, build adjacency carefully and guard against revisiting stale states. Use a visited or best-distance structure to avoid repeated work, and ensure unreachable scenarios return the required fallback value instead of partial traversal results.
Examples
With no transfers allowed, only the starting dock receives the announcement.
Docks 0, 1, and 2 form a reachable group within one transfer of the origin.
The crew may visit docks 0, 1, 2, and 3 before exceeding the transfer cap.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public int ferry_route_reach(int n, int[][] routes, int origin, int max_transfers) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) graph.put(i, new ArrayList<>());
for (int[] route : routes) {
graph.get(route[0]).add(route[1]);
graph.get(route[1]).add(route[0]);
}
Set<Integer> visited = new HashSet<>();
visited.add(origin);
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{origin, 0});
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int harbor = curr[0], transfers = curr[1];
if (transfers < max_transfers) {
for (int neighbor : graph.get(harbor)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.offer(new int[]{neighbor, transfers + 1});
}
}
}
}
return visited.size();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
