Mark As Completed Discussion

Dijkstra's algorithm is a well-known algorithm used to find the shortest path between two vertices in a weighted graph. It guarantees the shortest path from a source vertex to all other vertices. This algorithm is widely used in various applications, such as GPS navigation systems, network routing protocols, and airline travel planning.

The basic idea behind Dijkstra's algorithm is to continuously update the shortest path distances from the source vertex to all other vertices in the graph. It maintains a priority queue of vertices to explore, sorted by their current shortest distance from the source. At each step, it selects the vertex with the smallest current distance and relaxes the edges connected to it.

Let's take a look at an implementation of Dijkstra's algorithm in Java:

TEXT/X-JAVA
1class Graph {
2    private int V;
3    private int[][] graph;
4
5    public Graph(int V) {
6        this.V = V;
7        graph = new int[V][V];
8    }
9
10    public void addEdge(int src, int dest, int weight) {
11        graph[src][dest] = weight;
12    }
13
14    public void dijkstra(int source) {
15        // Initialize distance array
16        int[] dist = new int[V];
17        Arrays.fill(dist, Integer.MAX_VALUE);
18        dist[source] = 0;
19
20        // Initialize visited array
21        boolean[] visited = new boolean[V];
22
23        // Initialize priority queue
24        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> dist[a] - dist[b]);
25        pq.offer(source);
26
27        while (!pq.isEmpty()) {
28            int vertex = pq.poll();
29            visited[vertex] = true;
30
31            // Relax edges connected to the current vertex
32            for (int neighbor = 0; neighbor < V; neighbor++) {
33                int weight = graph[vertex][neighbor];
34
35                if (weight > 0 && !visited[neighbor]) {
36                    int newDistance = dist[vertex] + weight;
37
38                    if (newDistance < dist[neighbor]) {
39                        // Update shortest distance to neighbor
40                        dist[neighbor] = newDistance;
41
42                        // Add neighbor to priority queue
43                        pq.offer(neighbor);
44                    }
45                }
46            }
47        }
48
49        // Print the shortest distances from the source vertex
50        System.out.println(Arrays.toString(dist));
51    }
52
53    public static void main(String[] args) {
54        int V = 5; // Number of vertices
55        Graph graph = new Graph(V);
56
57        // Add edges
58        graph.addEdge(0, 1, 4);
59        graph.addEdge(0, 2, 1);
60        graph.addEdge(1, 3, 1);
61        graph.addEdge(2, 1, 2);
62        graph.addEdge(2, 3, 5);
63        graph.addEdge(3, 4, 3);
64
65        graph.dijkstra(0);
66    }
67}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment