-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
79 lines (68 loc) · 1.93 KB
/
DFS.java
File metadata and controls
79 lines (68 loc) · 1.93 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package algorithm.graph;
import java.util.LinkedList;
import java.util.Stack;
/**
* The type Dfs.
*/
public class DFS {
/**
* Dfs string.
*
* @param graph the graph
* @return the string
*/
public static String dfs(Graph graph) {
int vertices = graph.getVertices();
boolean[] visited = new boolean[vertices];
String result = "";
for (int i = 0; i < vertices; i++) {
if (!visited[i]) {
result += visitdfs(graph, i, visited);
}
}
return result;
}
private static String visitdfs(Graph graph, int source, boolean[] visited) {
String result = "";
Stack<Integer> stack = new Stack<>();
stack.push(source);
while (!stack.isEmpty()) {
int currentNode = stack.pop();
result += String.valueOf(currentNode);
LinkedList<Integer> temp = null;
if (graph.getAdj()[currentNode] != null) {
temp = graph.getAdj()[currentNode];
}
for (int i = 0; i < temp.size(); i++) {
if (!visited[temp.get(i)])
stack.push(temp.get(i));
}
visited[currentNode] = true;
}
return result;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
System.out.println("Graph1:");
g.printGraph();
System.out.println("DFS traversal of Graph1 : " + dfs(g));
System.out.println();
Graph g2 = new Graph(5);
g2.addEdge(0, 1);
g2.addEdge(0, 4);
g2.addEdge(1, 2);
g2.addEdge(4, 3);
System.out.println("Graph2:");
g2.printGraph();
System.out.println("DFS traversal of Graph2 : " + dfs(g2));
}
}