Approach
Breadth-first search
For Design Graph With Shortest Path Calculator, 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
- 46 lines of Java from the credited upstream file 2642.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 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 Graph {2 public Graph(int n, int[][] edges) {3 graph = new List[n];4 Arrays.setAll(graph, i -> new ArrayList<>());5 for (int[] edge : edges)6 addEdge(edge);7 }8 9 public void addEdge(int[] edge) {10 final int u = edge[0];11 final int v = edge[1];12 final int w = edge[2];13 graph[u].add(new Pair<>(v, w));14 }15 16 public int shortestPath(int node1, int node2) {17 int[] dist = new int[graph.length];18 Arrays.fill(dist, Integer.MAX_VALUE);19 20 Queue<Pair<Integer, Integer>> minHeap =21 new PriorityQueue<>(Comparator.comparingInt(Pair::getKey));22 23 dist[node1] = 0;24 minHeap.offer(new Pair<>(dist[node1], node1));25 26 while (!minHeap.isEmpty()) {27 final int d = minHeap.peek().getKey();28 final int u = minHeap.poll().getValue();29 if (u == node2)30 return d;31 for (Pair<Integer, Integer> pair : graph[u]) {32 final int v = pair.getKey();33 final int w = pair.getValue();34 if (d + w < dist[v]) {35 dist[v] = d + w;36 minHeap.offer(new Pair<>(dist[v], v));37 }38 }39 }40 41 return -1;42 }43 44 private List<Pair<Integer, Integer>>[] graph;45}46