-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathshortestPathInDag.java
More file actions
61 lines (48 loc) · 1.46 KB
/
Copy pathshortestPathInDag.java
File metadata and controls
61 lines (48 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Graphs;
import java.util.*;
public class shortestPathInDag {
public static int[] findShortestPath(ArrayList<ArrayList<Pair>> adj, int V, int source) {
int dist[] = new int[V];
for (int i = 0; i < V; i++)
dist[i] = Integer.MAX_VALUE;
dist[source] = 0;
Stack<Integer> s = new Stack<>();
findtopoSort(adj, V, s);
while (!s.isEmpty()) {
int node = s.pop();
if (dist[node] != Integer.MAX_VALUE) {
for (Pair it : adj.get(node)) {
if (dist[node] + it.weight < dist[it.node]) {
dist[it.node] = dist[node] + it.weight;
}
}
}
}
return dist;
}
public static void findtopoSort(ArrayList<ArrayList<Pair>> adj, int V, Stack<Integer> s) {
boolean vis[] = new boolean[V];
for (int i = 0; i < V; i++) {
if (vis[i] == false) {
dfs(i, vis, s, adj);
}
}
}
public static void dfs(int node, boolean vis[], Stack<Integer> s, ArrayList<ArrayList<Pair>> adj) {
vis[node] = true;
for (Pair it : adj.get(node)) {
if (vis[it.node] == false) {
dfs(it.node, vis, s, adj);
}
}
s.push(node);
}
}
class Pair {
int node;
int weight;
Pair(int node, int weight) {
this.node = node;
this.weight = weight;
}
}