-
Notifications
You must be signed in to change notification settings - Fork 104
/
Path.java
78 lines (57 loc) · 1.62 KB
/
Path.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.ArrayList;
import java.util.Collections;
public class Path {
private Graph G;
private int s, t;
private int[] pre;
private boolean[] visited;
public Path(Graph G, int s, int t){
G.validateVertex(s);
G.validateVertex(t);
this.G = G;
this.s = s;
this.t = t;
visited = new boolean[G.V()];
pre = new int[G.V()];
for(int i = 0; i < pre.length; i ++)
pre[i] = -1;
dfs(s, s);
for(boolean e: visited)
System.out.print(e + " ");
System.out.println();
}
private boolean dfs(int v, int parent){
visited[v] = true;
pre[v] = parent;
if(v == t) return true;
for(int w: G.adj(v))
if(!visited[w])
if(dfs(w, v))
return true;
return false;
}
public boolean isConnected(){
return visited[t];
}
public Iterable<Integer> path(){
ArrayList<Integer> res = new ArrayList<Integer>();
if(!isConnected()) 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");
Path path = new Path(g, 0, 6);
System.out.println("0 -> 6 : " + path.path());
Path path2 = new Path(g, 0, 5);
System.out.println("0 -> 5 : " + path2.path());
Path path3 = new Path(g, 0, 1);
System.out.println("0 -> 1 : " + path3.path());
}
}