diff --git "a/Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).java" "b/Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).java" new file mode 100644 index 000000000000..a3bb7622c46c --- /dev/null +++ "b/Dijkstra\342\200\231s Algorithm (Shortest Path in Weighted Graph).java" @@ -0,0 +1,49 @@ +import java.util.*; + +public class Dijkstra { + static class Node implements Comparable { + int vertex, weight; + Node(int v, int w) { vertex = v; weight = w; } + public int compareTo(Node other) { return this.weight - other.weight; } + } + + public static void dijkstra(int[][] graph, int src) { + int V = graph.length; + int[] dist = new int[V]; + Arrays.fill(dist, Integer.MAX_VALUE); + dist[src] = 0; + + PriorityQueue pq = new PriorityQueue<>(); + pq.add(new Node(src, 0)); + + while (!pq.isEmpty()) { + int u = pq.poll().vertex; + + for (int v = 0; v < V; v++) { + if (graph[u][v] != 0 && dist[u] + graph[u][v] < dist[v]) { + dist[v] = dist[u] + graph[u][v]; + pq.add(new Node(v, dist[v])); + } + } + } + + System.out.println("Vertex \t Distance from Source"); + for (int i = 0; i < V; i++) + System.out.println(i + "\t\t" + dist[i]); + } + + public static void main(String[] args) { + int[][] graph = { + {0, 4, 0, 0, 0, 0, 0, 8, 0}, + {4, 0, 8, 0, 0, 0, 0, 11, 0}, + {0, 8, 0, 7, 0, 4, 0, 0, 2}, + {0, 0, 7, 0, 9, 14, 0, 0, 0}, + {0, 0, 0, 9, 0, 10, 0, 0, 0}, + {0, 0, 4, 14, 10, 0, 2, 0, 0}, + {0, 0, 0, 0, 0, 2, 0, 1, 6}, + {8, 11, 0, 0, 0, 0, 1, 0, 7}, + {0, 0, 2, 0, 0, 0, 6, 7, 0} + }; + dijkstra(graph, 0); + } +}