Dijkstra's Algorithm for Single-Source Shortest Paths

Dijkstra's algorithm computes the shortest path distances from a designated source vertex to all other vertices in a weighted, directed or undirected graph with non-negative edge weights. It operates greedily: at each step, it selects the unvisited vertex with the smallest known distance from the source, marks it as visited, and relaxes (i.e., updates) the distances to its unvisited neighbors.

The correctness of selecting the minimum-distance unvisited vertex rests on two key observations:

  • No shorter path to that vertex can exist via other unvisited vertices — since all edge weights are non-negative, any detour through an unvisited node would only increase the total distnace.
  • No shorter path can exist via already-visited vertices — because their shortest distances have already been finalized and used to relax outgoing edges; thus, any indirect route through them would have already been considered and reflected in the current distance estimate.

Below is a restructured, self-contained implementation using descriptive naming, explicit initialization, and separation of concerns. The graph is loaded from a static adjacency matrix stored in row-major order.

import java.util.Scanner; import java.io.InputStream;

public class ShortestPathFinder {

private static final int INF = Integer.MAX_VALUE;

public static void main(String[] args) {
    ShortestPathFinder solver = new ShortestPathFinder();
    int[] distances = solver.computeMinDistancesFrom(0);
    for (int i = 0; i < distances.length; i++) {
        System.out.printf("Distance from node 0 to node %d: %d%n", i, distances[i]);
    }
}

public int[] computeMinDistancesFrom(int source) {
    int[][] graph = loadGraphMatrix();
    int n = graph.length;
    int[] dist = new int[n];
    boolean[] visited = new boolean[n];

    // Initialize distances
    for (int i = 0; i < n; i++) {
        dist[i] = (i == source) ? 0 : INF;
    }

    // Main loop: visit all nodes
    for (int count = 0; count < n; count++) {
        // Find unvisited node with minimum distance
        int closest = -1;
        int minDist = INF;
        for (int i = 0; i < n; i++) {
            if (!visited[i] && dist[i] < minDist) {
                minDist = dist[i];
                closest = i;
            }
        }

        if (closest == -1) break; // No reachable nodes left
        visited[closest] = true;

        // Relax edges from closest node
        for (int neighbor = 0; neighbor < n; neighbor++) {
            if (!visited[neighbor] && graph[closest][neighbor] != INF) {
                int newDist = dist[closest] + graph[closest][neighbor];
                if (newDist < dist[neighbor]) {
                    dist[neighbor] = newDist;
                }
            }
        }
    }

    return dist;
}

private int[][] loadGraphMatrix() {
    InputStream input = ShortestPathFinder.class.getResourceAsStream("/graph_weights.txt");
    Scanner scanner = new Scanner(input);
    int size = 8;
    int[][] matrix = new int[size][size];

    for (int i = 0; i < size; i++) {
        String[] tokens = scanner.nextLine().trim().split("\\s+");
        for (int j = 0; j < size; j++) {
            int val = Integer.parseInt(tokens[j]);
            matrix[i][j] = (val == 999) ? INF : val;
        }
    }
    return matrix;
}

}


</div>The corresponding `graph_weights.txt` file (placed under `src/main/resources/`) encodes an 8-vertex graph as folows — rows and columns index vertices 0 through 7; value `999` denotes absence of a direct edge (treated as infinity), and finite positive integerss represent edge weights:

<div>```
0 2 999 999 8 999 1 999
2 0 1 999 6 999 999 999
999 1 0 9 4 3 999 999
999 999 9 0 999 6 999 2
8 6 4 999 0 2 7 2
999 999 3 6 2 0 999 4
1 999 999 999 7 999 0 8
999 999 999 2 2 4 8 0

Tags: Dijkstra graph-algorithms shortest-path java

Posted on Tue, 18 Aug 2026 16:44:06 +0000 by Arya