1
1
/*
2
2
* This is a recursive implementation of the Depth-First Search (DFS) algorithm.
3
3
* DFS explores as far as possible along each branch before backtracking.
4
- *
5
- * For more details, refer to:
4
+ *
5
+ * For more details, refer to:
6
6
* https://en.wikipedia.org/wiki/Depth-first_search
7
7
*/
8
8
@@ -12,42 +12,37 @@ public class DFSrecursive {
12
12
13
13
private int [] visited ;
14
14
15
- //initializes the visited array for the number of vertices
16
- public DFSrecursive (int numVertices )
17
- {
18
- this .visited = new int [numVertices ];
15
+ // initializes the visited array for the number of vertices
16
+ public DFSrecursive (int numVertices ) {
17
+ this .visited = new int [numVertices ];
19
18
}
20
19
21
- //recursive dfs to check if there is a path from src to dest
22
- public boolean dfsPathCheck (graph g , int v , int dest )
23
- {
20
+ // recursive dfs to check if there is a path from src to dest
21
+ public boolean dfsPathCheck (Graph g , int v , int dest ) {
24
22
int numVertices = g .getNumVertices ();
25
- for (int w = 0 ; w < numVertices ; w ++)
26
- {
27
- if (g .adjacent (v , w ) && visited [w ] == -1 )
28
- {
23
+ for (int w = 0 ; w < numVertices ; w ++) {
24
+ if (g .adjacent (v , w ) && visited [w ] == -1 ) {
29
25
visited [w ] = v ;
30
- if (w == dest ){
26
+ if (w == dest ) {
31
27
return true ;
32
- }else if (dfsPathCheck (g , w , dest )){
28
+ } else if (dfsPathCheck (g , w , dest )) {
33
29
return true ;
34
30
}
35
- }
31
+ }
36
32
}
37
33
return false ;
38
34
}
39
35
40
- public boolean findPathDFS (graph g , int src , int dest )
41
- {
42
- Arrays .fill (visited , -1 );//reset visited array
36
+ public boolean findPathDFS (Graph g , int src , int dest ) {
37
+ Arrays .fill (visited , -1 ); // reset visited array
43
38
visited [src ] = src ;
44
39
return dfsPathCheck (g , src , dest );
45
40
}
46
41
47
42
public static void main (String [] args ) {
48
43
49
44
int V = 6 ;
50
- graph g = new graph (V );
45
+ Graph g = new Graph (V );
51
46
52
47
g .insertEdge (0 , 1 );
53
48
g .insertEdge (0 , 4 );
@@ -61,20 +56,16 @@ public static void main(String[] args) {
61
56
62
57
DFSrecursive dfs = new DFSrecursive (g .getNumVertices ());
63
58
int src = 0 , dest = 5 ;
64
- if (dfs .findPathDFS (g , src , dest ))
65
- {
59
+ if (dfs .findPathDFS (g , src , dest )) {
66
60
System .out .print ("Path found: " );
67
61
int v = dest ;
68
- while (v != src )
69
- {
62
+ while (v != src ) {
70
63
System .out .print (v + " <- " );
71
64
v = dfs .visited [v ];
72
65
}
73
66
System .out .println (src );
74
- }else {
67
+ } else {
75
68
System .out .println ("No path found from " + src + " to " + dest );
76
69
}
77
-
78
70
}
79
-
80
- }
71
+ }
0 commit comments