Skip to content

Commit c08727a

Browse files
author
techpanja
committed
Improved DFS.
Adding recursion.
1 parent ba58d82 commit c08727a

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

src/graphs/depthfirstsearch/DFS.java

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ private DFS() {
2323

2424
}
2525

26+
/*
27+
* DFS using Stack.
28+
* */
2629
public static void dfs(Graph graph) {
2730
Vertex vertex = graph.getFirstVertex();
2831
if (vertex != null) {
@@ -42,24 +45,52 @@ public static void dfs(Graph graph) {
4245
}
4346
}
4447

48+
// Improving the complexity of the solution by removing the temp from dependsOn.
4549
private static Vertex getUnvisitedVertex(Vertex vertex) {
4650
for (Vertex temp : vertex.getDependsOn()) {
4751
if (!temp.isVisited()) {
52+
vertex.getDependsOn().remove(temp);
4853
return temp;
4954
}
5055
}
5156
return null;
5257
}
5358

59+
/*
60+
* DFS using recursion.
61+
* */
62+
public static void dfsRecursion(Graph graph) {
63+
Vertex vertex = graph.getFirstVertex();
64+
dfs(vertex);
65+
}
66+
67+
public static void dfs(Vertex vertex) {
68+
if (vertex != null) {
69+
System.out.println(vertex);
70+
vertex.setVisited(true);
71+
for (Vertex temp : vertex.getDependsOn()) {
72+
if (!temp.isVisited()) {
73+
dfs(temp);
74+
}
75+
}
76+
77+
}
78+
}
79+
5480
public static void main(String[] args) {
5581
Graph graph = new DirectedGraph(6);
82+
// graph.addEdge("v1", "v2");
83+
// graph.addEdge("v2", "v3");
84+
// graph.addEdge("v3", "v4");
85+
// graph.addEdge("v1", "v5");
86+
// graph.addEdge("v1", "v6");
87+
5688
graph.addEdge("v1", "v2");
57-
graph.addEdge("v2", "v3");
58-
graph.addEdge("v3", "v4");
59-
graph.addEdge("v1", "v5");
60-
graph.addEdge("v1", "v6");
89+
graph.addEdge("v1", "v3");
90+
graph.addEdge("v2", "v4");
91+
6192
graph.displayGraphDependency();
62-
dfs(graph);
93+
dfsRecursion(graph);
6394
}
6495

6596
}

0 commit comments

Comments
 (0)