|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +public class DijkstraAlgorithm { |
| 4 | + static class Edge { |
| 5 | + int to; |
| 6 | + int weight; |
| 7 | + Edge(int t, int w) { |
| 8 | + to = t; |
| 9 | + weight = w; |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + public static int[] dijkstra(int n, List<List<Edge>> graph, int source) { |
| 14 | + int[] dist = new int[n]; |
| 15 | + Arrays.fill(dist, Integer.MAX_VALUE); |
| 16 | + dist[source] = 0; |
| 17 | + |
| 18 | + PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); |
| 19 | + pq.add(new int[]{source, 0}); |
| 20 | + |
| 21 | + boolean[] visited = new boolean[n]; |
| 22 | + |
| 23 | + while (!pq.isEmpty()) { |
| 24 | + int[] node = pq.poll(); |
| 25 | + int u = node[0]; |
| 26 | + |
| 27 | + if (visited[u]) continue; |
| 28 | + visited[u] = true; |
| 29 | + |
| 30 | + for (Edge e : graph.get(u)) { |
| 31 | + int v = e.to; |
| 32 | + int w = e.weight; |
| 33 | + if (dist[u] + w < dist[v]) { |
| 34 | + dist[v] = dist[u] + w; |
| 35 | + pq.add(new int[]{v, dist[v]}); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return dist; |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + int n = 6; |
| 44 | + List<List<Edge>> graph = new ArrayList<>(); |
| 45 | + for (int i = 0; i < n; i++) graph.add(new ArrayList<>()); |
| 46 | + |
| 47 | + graph.get(0).add(new Edge(1, 4)); |
| 48 | + graph.get(0).add(new Edge(2, 2)); |
| 49 | + graph.get(1).add(new Edge(3, 5)); |
| 50 | + graph.get(2).add(new Edge(1, 1)); |
| 51 | + graph.get(2).add(new Edge(3, 8)); |
| 52 | + graph.get(3).add(new Edge(4, 6)); |
| 53 | + graph.get(4).add(new Edge(5, 3)); |
| 54 | + |
| 55 | + int[] dist = dijkstra(n, graph, 0); |
| 56 | + |
| 57 | + for (int i = 0; i < n; i++) { |
| 58 | + System.out.println("Distance to " + i + " = " + dist[i]); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments