11package graph .undirected ;
22
3+ import graph .common .Graph ;
4+
35import java .util .Stack ;
46
57/**
1012 */
1113public class DFSPaths implements Paths {
1214 private boolean [] visited ; // vertex indexed array to mark when a vertex is visited
13- private int [] visitedFrom ; // vertex indexed array to track back from which vertex we reached a particular vertex for the first time
14- private int source ; // Stores the source vertex
15- private int sizeOfG ; // Stores the number of vertices in the graph to be processed
15+ private int [] edgeTo ; // vertex indexed array to track back from which vertex we reached a particular vertex for the first time
16+ private int source ; // source vertex
17+ private int sizeOfG ; // number of vertices in the graph
1618
1719 /**
1820 * Find paths in G from source vertex
@@ -24,7 +26,7 @@ public DFSPaths(Graph G, int source){
2426 validateVertex (source );
2527 this .source = source ;
2628 visited = new boolean [G .V ()];
27- visitedFrom = new int [G .V ()];
29+ edgeTo = new int [G .V ()];
2830 dfs (G , source );
2931 }
3032
@@ -52,23 +54,23 @@ public Iterable<Integer> pathTo(int v){
5254 int currentVertex = v ;
5355 while (currentVertex != this .source ){
5456 path .push (currentVertex );
55- currentVertex = visitedFrom [currentVertex ];
57+ currentVertex = edgeTo [currentVertex ];
5658 }
5759 path .push (this .source );
5860 return path ;
5961 }
6062
6163 /**
62- * Performs a DFS from source , to visit each vertex that has a path with source (undirected graph)
63- * @param G
64- * @param source
64+ * Performs a DFS from v , to visit each vertex that has a path with v (undirected graph)
65+ * @param G the graph on which DFS is to perform
66+ * @param v the vertex from which dfs is performed
6567 */
66- private void dfs (Graph G , int source ){
67- visited [source ] = true ;
68- for (int adjV : G .getAdjVertices (source )){
68+ private void dfs (Graph G , int v ){
69+ visited [v ] = true ;
70+ for (int adjV : G .getAdjVertices (v )){
6971 if (!visited [adjV ]){
7072 dfs (G , adjV );
71- visitedFrom [adjV ] = source ;
73+ edgeTo [adjV ] = v ;
7274 }
7375 }
7476 }
@@ -87,11 +89,6 @@ public static void main(String[] args){
8789 G .addEdge (3 , 4 );
8890
8991 DFSPaths DFSPathsFrom_0 = new DFSPaths (G , 0 );
90- for (int v : DFSPathsFrom_0 .pathTo (2 )){
91- System .out .print (" => " +v );
92- }
93- System .out .println ();
94-
95- System .out .println (DFSPathsFrom_0 .hasPathTo (2 ));
92+ System .out .println (DFSPathsFrom_0 .pathTo (3 ));
9693 }
9794}
0 commit comments