@@ -23,6 +23,9 @@ private DFS() {
23
23
24
24
}
25
25
26
+ /*
27
+ * DFS using Stack.
28
+ * */
26
29
public static void dfs (Graph graph ) {
27
30
Vertex vertex = graph .getFirstVertex ();
28
31
if (vertex != null ) {
@@ -42,24 +45,52 @@ public static void dfs(Graph graph) {
42
45
}
43
46
}
44
47
48
+ // Improving the complexity of the solution by removing the temp from dependsOn.
45
49
private static Vertex getUnvisitedVertex (Vertex vertex ) {
46
50
for (Vertex temp : vertex .getDependsOn ()) {
47
51
if (!temp .isVisited ()) {
52
+ vertex .getDependsOn ().remove (temp );
48
53
return temp ;
49
54
}
50
55
}
51
56
return null ;
52
57
}
53
58
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
+
54
80
public static void main (String [] args ) {
55
81
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
+
56
88
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
+
61
92
graph .displayGraphDependency ();
62
- dfs (graph );
93
+ dfsRecursion (graph );
63
94
}
64
95
65
96
}
0 commit comments