forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDFSrecursive.java
71 lines (61 loc) · 2.01 KB
/
DFSrecursive.java
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
/*
* This is a recursive implementation of the Depth-First Search (DFS) algorithm.
* DFS explores as far as possible along each branch before backtracking.
*
* For more details, refer to:
* https://en.wikipedia.org/wiki/Depth-first_search
*/
import java.util.Arrays;
public class DFSrecursive {
private int[] visited;
// initializes the visited array for the number of vertices
public DFSrecursive(int numVertices) {
this.visited = new int[numVertices];
}
// recursive dfs to check if there is a path from src to dest
public boolean dfsPathCheck(Graph g, int v, int dest) {
int numVertices = g.getNumVertices();
for (int w = 0; w < numVertices; w++) {
if (g.adjacent(v, w) && visited[w] == -1) {
visited[w] = v;
if (w == dest) {
return true;
} else if (dfsPathCheck(g, w, dest)) {
return true;
}
}
}
return false;
}
public boolean findPathDFS(Graph g, int src, int dest) {
Arrays.fill(visited, -1); // reset visited array
visited[src] = src;
return dfsPathCheck(g, src, dest);
}
public static void main(String[] args) {
int V = 6;
Graph g = new Graph(V);
g.insertEdge(0, 1);
g.insertEdge(0, 4);
g.insertEdge(0, 5);
g.insertEdge(5, 4);
g.insertEdge(4, 2);
g.insertEdge(4, 3);
g.insertEdge(5, 3);
g.insertEdge(1, 2);
g.insertEdge(3, 2);
DFSrecursive dfs = new DFSrecursive(g.getNumVertices());
int src = 0, dest = 5;
if (dfs.findPathDFS(g, src, dest)) {
System.out.print("Path found: ");
int v = dest;
while (v != src) {
System.out.print(v + " <- ");
v = dfs.visited[v];
}
System.out.println(src);
} else {
System.out.println("No path found from " + src + " to " + dest);
}
}
}