Table of contents
1.
Introduction
2.
Shortest Path Problem with Dijkstra's Algorithm Java
3.
How Dijkstra's Algorithm Works?
4.
Dijkstra Algorithm Steps
5.
Dijkstra Algorithm Pseudocode
6.
Implementation of Dijkstra's Algorithm in Java
7.
Dijkstra's Algorithm Complexity
7.1.
Time Complexity
7.2.
Space Complexity
8.
Limitations of the Dijkstra Algorithm
9.
Dijkstra's Algorithm Applications
10.
Frequently Asked Questions
10.1.
Can Dijkstra's algorithm handle graphs with negative edge weights?
10.2.
Is Dijkstra's algorithm efficient for large and dense graphs?
10.3.
Can Dijkstra's algorithm find the shortest paths from multiple source nodes?
11.
Conclusion
Last Updated: Sep 19, 2025
Easy

Dijkstra Algorithm Java

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Dijkstra's algorithm, which is named after its creator Edsger W. Dijkstra, is a fundamental algorithm in computer science that tackles the problem of finding the shortest path between nodes in a weighted graph. It has many applications in different domains, like navigation systems, network routing protocols, and finding the optimal path in transportation networks. 

The algorithm works by maintaining a set of visited nodes and iteratively selecting the node with the smallest distance from the starting point. It then updates the distances of the neighboring nodes if a shorter path is found through the current node. This process continues until all nodes are visited or the destination node is reached. 

Dijkstra Algorithm Java

In this article, we will discuss Dijkstra's algorithm in detail. We understand its working implementation in Java, analyze its time and space complexity, and finally discuss its limitations and applications. 

Shortest Path Problem with Dijkstra's Algorithm Java

The shortest path problem is a classic problem in graph theory that involves finding the path with the minimum total weight between two nodes in a weighted graph. Dijkstra's algorithm is an efficient solution to this problem, particularly when the graph has non-negative edge weights. It guarantees the shortest path from a single source node to all other nodes in the graph.


The problem can be formally defined as follows: Given a weighted graph G = (V, E) with a set of vertices V & a set of edges E, where each edge has a non-negative weight, & a starting node s, find the shortest path from s to every other node in the graph. The shortest path is defined as the path with the minimum sum of edge weights.


Dijkstra's algorithm solves this problem by maintaining a set of visited nodes and a distance array that keeps track of the shortest distance from the starting node to each node in the graph. It iteratively selects the unvisited node with the smallest distance and updates the distances of its neighboring nodes if a shorter path is found through the current node.


Java, a popular programming language, provides a suitable environment to implement Dijkstra's algorithm. We can represent the graph using an adjacency list or an adjacency matrix and use Java's built-in data structures, such as arrays, lists, and priority queues, to implement the algorithm efficiently.

How Dijkstra's Algorithm Works?

Dijkstra's algorithm is a greedy algorithm that finds the shortest path from a starting node to all other nodes in a weighted graph. It maintains a set of visited nodes and a distance array that keeps track of the shortest distance from the starting node to each node in the graph.

Let’s see a high-level overview of how Dijkstra's algorithm works:

1. Initialize the distance array: Set the distance of the starting node to 0 and the distances of all other nodes to infinity.
 

2. Create a set of unvisited nodes: Initially, all nodes are unvisited.
 

3. Select the unvisited node with the smallest distance: Choose the node with the minimum distance from the starting node among the unvisited nodes.
 

4. Update the distances of the neighboring nodes: For each unvisited neighbor of the current node, calculate the distance from the starting node to the neighbor through the current node. If this distance is smaller than the previously recorded distance, update the distance array.
 

5. Mark the current node as visited: Add the current node to the set of visited nodes.
 

6. Repeat steps 3-5 until all nodes are visited or the destination node is reached.


The algorithm maintains the shortest distance from the starting node to each node in the graph. At each iteration, it selects the unvisited node with the smallest distance and explores its neighbors. By updating the distances of the neighboring nodes if a shorter path is found, Dijkstra's algorithm ensures that it always finds the shortest path to each node.
 

Note: The algorithm terminates when all nodes are visited or when the destination node is reached. The distance array will contain the shortest distances from the starting node to all other nodes in the graph.

Dijkstra Algorithm Steps

Now, let's examine Dijkstra's algorithm step-by-step. We'll explain each step with a simple weighted graph.

Consider the below-weighted graph:

Dijkstra Algorithm Steps

Step 1: Initialize the distance array and the set of unvisited nodes.

- Set the distance of the starting node (e.g., node A) to 0.

- Set the distances of all other nodes to infinity.

- Mark all nodes as unvisited.

Distance array: [A: 0, B: ∞, C: ∞, D: ∞, E: ∞]
Unvisited nodes: {A, B, C, D, E}


Step 2: Select the unvisited node with the smallest distance.

- In the first iteration, node A has the smallest distance (0).

Current node: A


Step 3: Update the distances of the neighboring nodes.

- Explore the neighbors of node A (B & C).
 

- Calculate the distance from A to B (0 + 4 = 4) & from A to C (0 + 2 = 2).
 

- Update the distance array if a shorter path is found.

Distance array: [A: 0, B: 4, C: 2, D: ∞, E: ∞]


Step 4: Mark the current node as visited.

- Add node A to the set of visited nodes.

Visited nodes: {A}
Unvisited nodes: {B, C, D, E}


Step 5: Repeat steps 2-4 until all nodes are visited or the destination node is reached.

- Select the unvisited node with the smallest distance (node C).

- Update the distances of its neighbors (D & E).

- Mark node C as visited.


(Continue the process until all nodes are visited)

Final distance array: [A: 0, B: 4, C: 2, D: 5, E: 6]


The final distance array represents the shortest distances from the starting node (A) to all other nodes in the graph.

Dijkstra Algorithm Pseudocode

Now that we understand Dijkstra's algorithm, let's look at its pseudocode. The pseudocode gives a high-level description of the algorithm with a generic programming language-like syntax.

function dijkstra(graph, startNode):
    create distance array
    create visited set
    
    for each node in graph:
        distance[node] = INFINITY
        visited[node] = false
    
    distance[startNode] = 0
    
    while there are unvisited nodes:
        currentNode = node with smallest distance among unvisited nodes
        
        if currentNode == INFINITY:
            break
        
        visited[currentNode] = true
        
        for each neighbor of currentNode:
            if !visited[neighbor]:
                tentativeDistance = distance[currentNode] + edgeWeight(currentNode, neighbor)
                if tentativeDistance < distance[neighbor]:
                    distance[neighbor] = tentativeDistance
    
    return distance


In this pseudocode: 

1. The function `dijkstra` takes the graph & the starting node as input.
 

2. It creates a distance array to store the shortest distances from the starting node to all other nodes. Initially, all distances are set to INFINITY, except for the starting node, which has a distance of 0.
 

3. It also creates a visited set to keep track of the nodes that have been visited.
 

4. The algorithm enters a loop that continues until all nodes are visited or there are no more reachable unvisited nodes.
 

5. In each iteration, it selects the unvisited node with the smallest distance (currentNode).
 

6. If currentNode has a distance of INFINITY, it means there are no more reachable unvisited nodes, and the algorithm terminates.
 

7. It marks the currentNode as visited.
 

8. For each unvisited neighbor of currentNode, it calculates the tentative distance from the starting node to the neighbor through currentNode.
 

9. If the tentative distance is smaller than the current distance to the neighbor, it updates the distance array with the new shortest distance.
 

10. The algorithm repeats steps 5-9 until all nodes are visited or there are no more reachable unvisited nodes.
 

11. Finally, it returns the distance array containing the shortest distances from the starting node to all other nodes.

Implementation of Dijkstra's Algorithm in Java

import java.util.*;
public class DijkstraAlgorithm {
    private static final int INF = Integer.MAX_VALUE;
    
    public static void dijkstra(int[][] graph, int startNode) {
        int numNodes = graph.length;
        int[] distance = new int[numNodes];
        boolean[] visited = new boolean[numNodes];
        
        // Initialize distances and visited array
        Arrays.fill(distance, INF);
        distance[startNode] = 0;
        
        for (int i = 0; i < numNodes - 1; i++) {
            int currentNode = findMinDistance(distance, visited);
            visited[currentNode] = true;
            
            for (int j = 0; j < numNodes; j++) {
                if (!visited[j] && graph[currentNode][j] != 0 &&
                    distance[currentNode] != INF &&
                    distance[currentNode] + graph[currentNode][j] < distance[j]) {
                    distance[j] = distance[currentNode] + graph[currentNode][j];
                }
            }
        }
        
        // Print the shortest distances
        printSolution(distance);
    }
    
    private static int findMinDistance(int[] distance, boolean[] visited) {
        int minDistance = INF;
        int minIndex = -1;
        
        for (int i = 0; i < distance.length; i++) {
            if (!visited[i] && distance[i] < minDistance) {
                minDistance = distance[i];
                minIndex = i;
            }
        }
        
        return minIndex;
    }
    
    private static void printSolution(int[] distance) {
        System.out.println("Shortest distances from the starting node:");
        for (int i = 0; i < distance.length; i++) {
            System.out.println("Node " + i + ": " + distance[i]);
        }
    }
    
    public static void main(String[] args) {
        int[][] graph = {
            {0, 4, 2, 0, 0},
            {4, 0, 0, 3, 0},
            {2, 0, 0, 1, 5},
            {0, 3, 1, 0, 0},
            {0, 0, 5, 0, 0}
        };
        
        int startNode = 0; // Starting node (A)
        
        dijkstra(graph, startNode);
    }
}
You can also try this code with Online Java Compiler
Run Code


In this code, we represent the graph using a 2D array (`graph`) where `graph[i][j]` represents the weight of the edge between nodes i and j. If there is no direct edge between two nodes, the weight is set to 0.


The `dijkstra` method takes the graph and the starting node as input. It initializes the `distance` array with INF (infinity) for all nodes except the starting node, which has a distance of 0. It also initializes the `visited` array to keep track of visited nodes.


The algorithm then enters a loop that runs for `numNodes - 1` iterations. In each iteration, it finds the unvisited node with the minimum distance using the `findMinDistance` method and marks it as visited. It then updates the distances of its neighboring nodes if a shorter path is found.


The `findMinDistance` method iterates through the `distance` array and returns the index of the unvisited node with the minimum distance.


After the loop ends, the `printSolution` method is called to print the shortest distances from the starting node to all other nodes.


In the `main` method, we define the graph using a 2D array and specify the starting node. We then call the `dijkstra` method to find the shortest distances.


Output:

Shortest distances from the starting node:
Node 0: 0
Node 1: 4
Node 2: 2
Node 3: 3
Node 4: 6


The output shows the shortest distances from the starting node (A) to all other nodes in the graph.

Dijkstra's Algorithm Complexity

Time Complexity

The time complexity of Dijkstra's algorithm depends on the implementation and the data structures used. In the implementation above, we used an adjacency matrix to represent the graph and a linear search to find the node with the minimum distance.

The main steps contributing to the time complexity are:

1. Initializing the distance & visited arrays: O(V), where V is the number of vertices (nodes) in the graph.
 

2. The main loop iterates V-1 times, & in each iteration:
 

   - Finding the node with the minimum distance using linear search: O(V).
 

   - Updating the distances of the neighboring nodes: O(V).
 

Therefore, the overall time complexity is O(V^2), where V is the number of vertices in the graph.

 

Note: The time complexity can be improved by using more efficient data structures. For example, if we use a min-heap (priority queue) to find the node with the minimum distance, the time complexity becomes O((V+E) log V), where E is the number of edges in the graph.

Space Complexity

The space complexity of Dijkstra's algorithm is determined by the data structures used to represent the graph and the additional arrays used in the algorithm.

In the code above, we used:

- An adjacency matrix to represent the graph: O(V^2) space.
 

- Distance array to store the shortest distances: O(V) space.
 

- Visited array to keep track of visited nodes: O(V) space.
 

Therefore, the overall space complexity is O(V^2) due to the adjacency matrix representation.
 

However, if an adjacency list is used instead of an adjacency matrix, the space complexity can be reduced to O(V+E), where E is the number of edges in the graph.


Always Remember: The choice of data structures can significantly impact the time and space complexity of Dijkstra's algorithm. The adjacency matrix representation provides faster access to edge weights but requires more space, while the adjacency list representation is more space-efficient but may have slower access to edge weights.

Limitations of the Dijkstra Algorithm

1. Non-negative edge weights: Dijkstra's algorithm assumes that all edge weights in the graph are non-negative. If the graph contains negative edge weights, the algorithm may not correctly find the shortest paths. In such cases, algorithms like the Bellman-Ford algorithm or the Floyd-Warshall algorithm can be used instead.
 

2. Graphs with cycles: Dijkstra's algorithm works correctly on graphs with cycles, as long as the edge weights are non-negative. However, if the graph contains cycles with negative weights, the algorithm may get stuck in an infinite loop or produce incorrect results. In such cases, additional checks or modifications to the algorithm are required.
 

3. Efficiency on dense graphs: Dijkstra's algorithm has a time complexity of O(V^2) when using an adjacency matrix representation, where V is the number of vertices. For dense graphs with a large number of edges, this quadratic time complexity can be inefficient. Using a min-heap (priority queue) implementation can improve the time complexity to O((V+E) log V), but it may still be slow for very large and dense graphs.
 

4. Memory usage: Dijkstra's algorithm requires additional memory to store the distance array, visited array, and graph representation. For large graphs, memory usage can be significant, especially when using an adjacency matrix representation. Using an adjacency list representation can reduce memory usage, but it may still be a limitation for extremely large graphs.
 

5. Single-source shortest paths: Dijkstra's algorithm computes the shortest paths from a single source node to all other nodes in the graph. If the shortest paths from multiple source nodes are required, the algorithm must be run separately for each source node, which can be inefficient. In such cases, algorithms like the Floyd-Warshall algorithm or Johnson's algorithm may be more suitable.
 

6. Real-time updates: Dijkstra's algorithm is designed for static graphs where the edge weights do not change during execution. If the graph undergoes real-time updates, such as changes in edge weights or the addition/removal of nodes or edges, the algorithm needs to be rerun from scratch. In scenarios where frequent real-time updates are required, incremental or dynamic shortest-path algorithms may be more appropriate.

Dijkstra's Algorithm Applications

1. Shortest path navigation: Dijkstra's algorithm is widely used in navigation systems, such as GPS devices and mapping software, to find the shortest path between two locations. By representing the road network as a weighted graph, with intersections as nodes and road segments as edges, Dijkstra's algorithm can efficiently compute the shortest path from a starting point to a destination, considering factors like distance, travel time, or traffic conditions.
 

2. Network routing: In computer networks, Dijkstra's algorithm finds the shortest path for data packets to travel from a source node to a destination node. It helps determine the most efficient route for data transmission, minimizing latency and maximizing network performance. Dijkstra's algorithm is utilized in various network routing protocols, such as OSPF (Open Shortest Path First) and IS-IS (Intermediate System to Intermediate System).
 

3. Flight itinerary optimization: Airlines and travel agencies use Dijkstra's algorithm to optimize flight itineraries for customers. By representing airports as nodes and flights as edges with associated costs (e.g., ticket prices, travel time), Dijkstra's algorithm can find the most cost-effective or time-efficient route between two cities, considering multiple flight options and layovers.
 

4. Supply chain optimization: In supply chain management, Dijkstra's algorithm is used to optimize the transportation of goods from suppliers to customers. By modeling the supply chain network as a weighted graph, with warehouses, distribution centers, and retail stores as nodes and transportation routes as edges, Dijkstra's algorithm can determine the shortest or most cost-effective path for product distribution, minimizing transportation costs and delivery times.
 

5. Resource allocation: Dijkstra's algorithm can be applied to resource allocation problems, such as task scheduling or resource assignment. By representing tasks or resources as nodes and dependencies or constraints as edges, Dijkstra's algorithm can find the optimal allocation that minimizes the overall cost or maximizes resource utilization.
 

6. Social network analysis: Dijkstra's algorithm finds the shortest paths between individuals or communities. By representing people as nodes and their relationships or interactions as edges, Dijkstra's algorithm can identify the most influential nodes, detect communities, or analyze the spread of information or influence within the network.
 

7. Robotics and path planning: In robotics, Dijkstra's algorithm is used for path planning and navigation. By representing the environment as a weighted graph, with obstacles and free spaces as nodes and edges, Dijkstra's algorithm can compute the shortest or most efficient path for a robot to navigate from a starting position to a target position, avoiding obstacles and optimizing the robot's movements.

Frequently Asked Questions

Can Dijkstra's algorithm handle graphs with negative edge weights?

No, Dijkstra's algorithm assumes non-negative edge weights. For graphs with negative edge weights, algorithms like the Bellman-Ford algorithm or the Floyd-Warshall algorithm should be used instead.

Is Dijkstra's algorithm efficient for large and dense graphs?

Dijkstra's algorithm has a time complexity of O(V^2) using an adjacency matrix, which can be inefficient for large and dense graphs. Using a min-heap (priority queue) implementation improves the time complexity to O((V+E) log V), but it may still be slow for very large graphs. Alternative algorithms or graph representations may be more suitable in such cases.

Can Dijkstra's algorithm find the shortest paths from multiple source nodes?

No, Dijkstra's algorithm computes the shortest paths from a single source node to all other nodes. To find the shortest paths from multiple source nodes, the algorithm needs to be run separately for each source node. Algorithms like the Floyd-Warshall algorithm or Johnson's algorithm are more suitable for finding all-pairs shortest paths.

Conclusion

In this article, we discussed Dijkstra's algorithm in detail, a fundamental algorithm for finding the shortest paths in weighted graphs. We discussed its step-by-step workings, provided a Java implementation, analyzed its time and space complexity, and highlighted its limitations. We also showcased its different applications in various domains. Dijkstra's algorithm is a powerful tool for efficiently solving shortest-path problems.

Live masterclass