Repository navigation
Expand file tree
/
Copy pathBB2.java
More file actions
92 lines (71 loc) · 2.66 KB
/
Copy pathBB2.java
File metadata and controls
92 lines (71 loc) · 2.66 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.*;
public class BB2 {
private Map<Character, Set<Character>> routes;
public BB2() {
this.routes = new HashMap<>();
}
public void addPath(char start, char end) {
this.routes.putIfAbsent(start, new HashSet<>());
this.routes.putIfAbsent(end, new HashSet<>());
this.routes.get(start).add(end);
this.routes.get(end).add(start);
}
public List<String> printAllPathsBetween(char start, char end) {
List<String> result = new ArrayList<>();
List<Character> currPath = new ArrayList<>();
Set<Character> visited = new HashSet<>();
currPath.add(start);
visited.add(start);
dfs(routes, visited, result, currPath, start, end);
return result;
}
private void dfs(Map<Character, Set<Character>> routes, Set<Character> visited, List<String> result,
List<Character> currPath, Character start, Character end) {
if (start == end) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < currPath.size(); i++) {
sb.append(currPath.get(i));
if (i != currPath.size() - 1) {
sb.append(" -> ");
}
}
result.add(sb.toString());
return;
}
for (Character neighbour : routes.get(start)) {
if (!visited.contains(neighbour)) {
visited.add(neighbour);
currPath.add(neighbour);
dfs(routes, visited, result, currPath, neighbour, end);
visited.remove(neighbour);
currPath.remove(currPath.size() - 1);
}
}
}
public static void main(String[] args) {
BB2 graph = new BB2();
graph.addPath('A', 'B');
graph.addPath('B', 'C');
graph.addPath('B', 'C');
graph.addPath('A', 'C');
graph.addPath('A', 'D');
graph.addPath('D', 'C');
graph.addPath('F', 'E');
List<String> validPathFromAtoC = graph.printAllPathsBetween('A', 'C');
List<String> validPathFromBtoD = graph.printAllPathsBetween('B', 'D');
List<String> invalidPathFromEtoA = graph.printAllPathsBetween('E', 'A');
System.out.println("Valid Path - A to C:");
for (String p : validPathFromAtoC) {
System.out.println(p);
}
System.out.println("\nValid Path - B to D:");
for (String p : validPathFromBtoD) {
System.out.println(p);
}
System.out.println("\nInvalid Path - E to A:");
for (String p : invalidPathFromEtoA) {
System.out.println(p);
}
return;
}
}