-
Notifications
You must be signed in to change notification settings - Fork 104
/
GraphDFS.java
45 lines (34 loc) · 989 Bytes
/
GraphDFS.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
import java.util.ArrayList;
public class GraphDFS {
private Graph G;
private boolean[] visited;
private ArrayList<Integer> pre = new ArrayList<>();
private ArrayList<Integer> post = new ArrayList<>();
public GraphDFS(Graph G){
this.G = G;
visited = new boolean[G.V()];
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
dfs(v);
}
private void dfs(int v){
visited[v] = true;
pre.add(v);
for(int w: G.adj(v))
if(!visited[w])
dfs(w);
post.add(v);
}
public Iterable<Integer> pre(){
return pre;
}
public Iterable<Integer> post(){
return post;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
GraphDFS graphDFS = new GraphDFS(g);
System.out.println("DFS preOrder : " + graphDFS.pre());
System.out.println("DFS postOrder : " + graphDFS.post());
}
}