From 41efb7277792e9d1502d305cfd706dd514e24663 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Mon, 5 Jul 2021 14:38:04 -0500 Subject: Dijkstra shortest path done, using PriorityQueue. Don't give up! Very rewarding! --- src/main/Dijkstra.java | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ src/main/PlayGround.java | 13 ++++++++++ 2 files changed, 77 insertions(+) create mode 100644 src/main/Dijkstra.java create mode 100644 src/main/PlayGround.java (limited to 'src/main') diff --git a/src/main/Dijkstra.java b/src/main/Dijkstra.java new file mode 100644 index 0000000..5bc31b0 --- /dev/null +++ b/src/main/Dijkstra.java @@ -0,0 +1,64 @@ +import java.util.*; + +public class Dijkstra { + static int distance(ArrayList[] adj, ArrayList[] cost, int s, int t) { + if (s == t) + return 0; + int[] dist = new int[adj.length]; + //int[] prev = new int[adj.length]; + boolean[] visited = new boolean[adj.length]; + for (int i = 0; i < dist.length; i++) { + dist[i] = Integer.MAX_VALUE; + //prev[i] = -1; + } + + dist[s] = 0; + + PriorityQueue vertexQ; + vertexQ = new PriorityQueue(Comparator.comparingInt(a -> dist[a])); + vertexQ.add(s); + + while (!vertexQ.isEmpty()) { + int u = vertexQ.remove(); + if (visited[u]) { + continue; + } + visited[u] = true; + if (adj[u].size() > 0) { + for (int i = 0; i < adj[u].size(); i++) { + if (dist[adj[u].get(i)] > dist[u] + cost[u].get(i)) { + dist[adj[u].get(i)] = dist[u] + cost[u].get(i); + //prev[adj[u].get(i)] = u; + vertexQ.add(adj[u].get(i)); + } + } + } + } + if (dist[t] == Integer.MAX_VALUE) + return -1; + return dist[t]; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + int n = scanner.nextInt(); + int m = scanner.nextInt(); + ArrayList[] adj = (ArrayList[]) new ArrayList[n]; + ArrayList[] cost = (ArrayList[]) new ArrayList[n]; + for (int i = 0; i < n; i++) { + adj[i] = new ArrayList(); + cost[i] = new ArrayList(); + } + for (int i = 0; i < m; i++) { + int x, y, w; + x = scanner.nextInt(); + y = scanner.nextInt(); + w = scanner.nextInt(); + adj[x - 1].add(y - 1); + cost[x - 1].add(w); + } + int x = scanner.nextInt() - 1; + int y = scanner.nextInt() - 1; + System.out.println(distance(adj, cost, x, y)); + } +} \ No newline at end of file diff --git a/src/main/PlayGround.java b/src/main/PlayGround.java new file mode 100644 index 0000000..14a4c80 --- /dev/null +++ b/src/main/PlayGround.java @@ -0,0 +1,13 @@ +import java.util.PriorityQueue; +import java.util.HashMap; +public class PlayGround { + static int testPriorityQueue() { + PriorityQueue numbers = new PriorityQueue<>(); + numbers.add(7); + numbers.add(5); + numbers.add(8); + numbers.add(3); + return numbers.poll(); + } + +} -- cgit v1.2.3