-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphTraversal.java
55 lines (51 loc) · 1.8 KB
/
GraphTraversal.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
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Stack;
public class GraphTraversal {
public static void main(String[] args) {
GraphTraversal tester = new GraphTraversal();
Map<String, List<String>> graph = new HashMap<>();
graph.put("A", List.of("C", "B"));
graph.put("B", List.of("D"));
graph.put("C", List.of("E"));
graph.put("D", List.of("F"));
graph.put("E", List.of());
graph.put("F", List.of());
tester.printDfs(graph, "A");
System.out.println("");
tester.printRecurssiveDfs(graph, "A");
System.out.println("");
tester.printBfs(graph, "A");
}
private void printBfs(Map<String, List<String>> graph, String start) {
Queue<String> queue = new LinkedList<>();
queue.add(start);
while (!queue.isEmpty()) {
String current = queue.poll();
System.out.print(current + " ");
List<String> neighbors = graph.get(current);
neighbors.forEach(queue::add);
}
}
void printDfs(Map<String, List<String>> graph, String start) {
Stack<String> stack = new Stack<>();
stack.push(start);
while (!stack.isEmpty()) {
String current = stack.pop();
System.out.print(current + " ");
List<String> neighbors = graph.get(current);
neighbors.forEach(stack::push);
}
}
void printRecurssiveDfs(Map<String, List<String>> graph, String start) {
System.out.print(start + " ");
List<String> neighbors = graph.get(start);
if (neighbors.isEmpty()) return;
for (String neighbor:neighbors) {
printRecurssiveDfs(graph, neighbor);
}
}
}