-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathSingleSourcePath.java
58 lines (43 loc) · 1.21 KB
/
SingleSourcePath.java
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
import java.util.ArrayList;
import java.util.Collections;
public class SingleSourcePath {
private Graph G;
private int s;
private int[] pre;
public SingleSourcePath(Graph G, int s){
this.G = G;
this.s = s;
pre = new int[G.V()];
for(int i = 0; i < pre.length; i ++)
pre[i] = -1;
dfs(s, s);
}
private void dfs(int v, int parent){
pre[v] = parent;
for(int w: G.adj(v))
if(pre[w] == -1)
dfs(w, v);
}
public boolean isConnectedTo(int t){
G.validateVertex(t);
return pre[t] != -1;
}
public Iterable<Integer> path(int t){
ArrayList<Integer> res = new ArrayList<Integer>();
if(!isConnectedTo(t)) return res;
int cur = t;
while(cur != s){
res.add(cur);
cur = pre[cur];
}
res.add(s);
Collections.reverse(res);
return res;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
SingleSourcePath sspath = new SingleSourcePath(g, 0);
System.out.println("0 -> 6 : " + sspath.path(6));
System.out.println("0 -> 5 : " + sspath.path(5));
}
}