JAVA PROGRAM • LEVEL 17 — DATA STRUCTURES & ALGORITHMS IN JAVA
Find Shortest Paths with Dijkstra in Java
Learn find shortest paths with dijkstra in java with a complete, compiler-ready Java 17 example.
PROBLEM UNDERSTANDING
Input and expected output
No input required
[0, 3, 1]
COMPLETE JAVA 17 PROGRAM
Complete Java 17 implementation
import java.util.*;class Main{public static void main(String[] args){int[][] w={{0,4,1},{4,0,2},{1,2,0}};int[] d={0,999,999};boolean[] used=new boolean[3];for(int step=0;step<3;step++){int u=-1;for(int i=0;i<3;i++)if(!used[i]&&(u==-1||d[i]<d[u]))u=i;used[u]=true;for(int v=0;v<3;v++)if(w[u][v]>0)d[v]=Math.min(d[v],d[u]+w[u][v]);}System.out.println(Arrays.toString(d));}}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
[0, 3, 1]
PROGRAM EXPLANATION
Algorithm and explanation
- Initialize the deterministic sample values used for find shortest paths with dijkstra in java.
- Apply Dijkstra and Relaxation in the order shown by the program.
- Print the final result and compare it with the documented sample output.
This Java 17 example demonstrates Dijkstra and Relaxation through a complete, executable program. The values are intentionally small so students can trace each statement, verify the output, and then modify the example safely in the online compiler.
EFFICIENCY
Time and space complexity
O(V²)
O(V)
DEBUGGING CHECKLIST
Common mistakes
Keep the class name Main and the entry method signature public static void main(String[] args) when using the online compiler.
Check the loop boundary and update expression carefully to avoid skipping the final value or creating an infinite loop.
Java is case-sensitive, and every statement that requires a semicolon must end with one.
