forked from anku580/Java-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFSgraph.java
More file actions
56 lines (46 loc) · 1.14 KB
/
DFSgraph.java
File metadata and controls
56 lines (46 loc) · 1.14 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
import java.util.LinkedList;
import java.util.Stack;
public class DFSgraph {
private boolean[] marked;
private int[] edgeTo;
private int s;
public Stack<Integer> stk = new Stack<>();
DFSgraph(Graph g, int s) {
marked = new boolean[g.V()];
edgeTo = new int[g.V()];
this.s = s;
dfs(g, s);
}
public void dfs(Graph g, int v) {
marked[v] = true;
for (int w : g.adj(v)) {
if (!marked[w]) {
dfs(g, w);
edgeTo[w] = v;
}
}
}
public void printEle(int d) {
stk.push(d);
do {
stk.push(edgeTo[d]);
d = edgeTo[d];
} while (d != s);
while (!stk.isEmpty()) {
System.out.println(stk.pop());
}
}
public static void main(String args[]) {
Graph g = new Graph(7);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 5);
g.addEdge(0, 6);
g.addEdge(5, 3);
g.addEdge(5, 4);
g.addEdge(3, 4);
g.addEdge(4, 6);
DFSgraph d = new DFSgraph(g, 0);
d.printEle(3);
}
}