Implementing Dijkstra's Algorithm

JavaJavaBeginner
Practice Now

Introduction

In this lab, we're going to implement Dijkstra's Algorithm in Java. Dijkstra's Algorithm is a popular algorithm used to solve the shortest-path problem for a weighted graph.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/booleans("`Booleans`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/recursion -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/scope -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/classes_objects -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/class_methods -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/modifiers -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/oop -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/wrapper_classes -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/identifier -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/arrays -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/booleans -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/comments -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/data_types -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/for_loop -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/if_else -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/operators -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/output -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/variables -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/arrays_methods -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/object_methods -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} java/system_methods -.-> lab-117406{{"`Implementing Dijkstra's Algorithm`"}} end

Create a Graph Class

In this step, we'll create a class called Graph that will represent our weighted graph. We'll create a 2-D adjacency matrix in this class to represent the edges of the graph.

class Graph
{
    int[][] adjMatrix; // adjacency matrix to represent the edges
    int numOfvertices;

    Graph(int[][] mat, int v)
    {
        this.adjMatrix = mat;
        this.numOfvertices = v;
    }

    void addEdge(int src, int dest, int edgeWeight)
    {
        adjMatrix[src][dest] = edgeWeight;
        adjMatrix[dest][src] = edgeWeight;
    }
}

Implement Dijkstra's Algorithm

In this step, we'll implement Dijkstra's algorithm in Java. Let's create a helper method called getClosestVertex to find the closest unvisited node. We'll also implement the main algorithm in a dijkstrasShortestPath method. This method will take a Graph and a source vertex as parameters and return the shortest-distance array.

public static int getClosestVertex(int[] distance, boolean[] visited) {
    int min = Integer.MAX_VALUE;
    int minIdx = -1;
    for(int i=0; i<distance.length; i++) {
        if(distance[i] < min)
            if(visited[i] == false) {
                min = distance[i];
                minIdx = i;
            }
    }
    return minIdx;
}

public static int[] dijkstrasShortestPath(Graph g, int src) {
    // final shortest distance array
    int[] distance = new int[g.numOfvertices];
    // array to tell whether shortest distance of vertex has been found
    boolean[] visited = new boolean[g.numOfvertices];

    // initializing the arrays
    for(int i=0; i<g.numOfvertices; i++) {
        distance[i] = Integer.MAX_VALUE; // initial distance is infinite
        visited[i] = false; // shortest distance for any node has not been found yet
    }
    distance[src] = 0;

    for(int i=0; i<g.numOfvertices; i++) {
        int closestVertex = getClosestVertex(distance, visited); // get the closest node
        if(closestVertex == Integer.MAX_VALUE) // if closest node is infinite distance away, it means that no other node can be reached. So return
            return distance;

        visited[closestVertex] = true;
        for(int j=0; j<g.numOfvertices; j++) {
            if(visited[j] == false) // shortest distance of the node j should not have been finalized
            {
                if(g.adjMatrix[closestVertex][j] != 0) {
                    int d = distance[closestVertex] + g.adjMatrix[closestVertex][j];
                    if(d < distance[j]) // distance via closestVertex is less than the initial distance
                        distance[j] = d;
                }
            }
        }
    }
    return distance;
}

Test Our Implementation

In this step, we'll test our implementation by creating a main method that will add edges to our graph and call our dijkstrasShortestPath method to find the shortest distance from a source vertex to all other vertices of a weighted graph.

public static void main(String[] args) {
    int numOfVertices = 6;
    int[][] adjMat = new int[6][6];
    Graph graph = new Graph(adjMat, numOfVertices);

    // add edges to the graph
    graph.addEdge(0, 4, 21);
    graph.addEdge(0, 3, 18);
    graph.addEdge(2, 1, 7);
    graph.addEdge(1, 4, 6);
    graph.addEdge(4, 5, 10);
    graph.addEdge(4, 3, 11);
    graph.addEdge(5, 3, 7);

    // call Dijkstra's algorithm to find shortest distance
    int[] dist = dijkstrasShortestPath(graph, 0);
    System.out.print(Arrays.toString(dist));
}

Compile and run the above code to get the shortest-distance array [0, 27, 34, 18, 21, 25].

Summary

Congratulations! You have completed the Implementing Dijkstra's Algorithm lab. You can practice more labs in LabEx to improve your skills.

Other Java Tutorials you may like