-
Notifications
You must be signed in to change notification settings - Fork 2
/
DepthFirstSearchRecursive.java
63 lines (53 loc) · 1.66 KB
/
DepthFirstSearchRecursive.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
package Graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author kalpak
*
* DFS Traversal on a Graph - Recursive
*/
public class DepthFirstSearchRecursive {
static class Edge {
int from, to, cost;
public Edge(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
}
// Helper method to setup graph
private static void addDirectedEdge(Map<Integer, List<Edge>> graph, int from, int to, int cost) {
List<Edge> list = graph.get(from);
if (list == null) {
list = new ArrayList<Edge>();
graph.put(from, list);
}
list.add(new Edge(from, to, cost));
}
public static void dfsRecursive(int start, boolean[] isVisited, Map<Integer, List<Edge>> graph) {
if(isVisited[start])
return;
isVisited[start] = true;
System.out.print(start + " ");
List<Edge> adjacencyList = graph.get(start);
if(adjacencyList != null) {
for(Edge edge : adjacencyList) {
dfsRecursive(edge.to, isVisited, graph);
}
}
return;
}
public static void main(String[] args) {
int numNodes = 5;
Map<Integer, List<Edge>> graph = new HashMap<>();
addDirectedEdge(graph, 0, 1, 4);
addDirectedEdge(graph, 0, 2, 5);
addDirectedEdge(graph, 1, 2, -2);
addDirectedEdge(graph, 1, 3, 6);
addDirectedEdge(graph, 2, 3, 1);
addDirectedEdge(graph, 2, 2, 10); // Self loop
dfsRecursive(0, new boolean[numNodes], graph);
}
}