Skip to content

Commit 1f87c3f

Browse files
committed
Add BreadthFirstSearch
1 parent 88e904c commit 1f87c3f

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package algorithm;
2+
3+
import java.util.*;
4+
5+
import static java.util.function.Predicate.not;
6+
import static java.util.stream.Stream.iterate;
7+
8+
public class BreadthFirstSearch<T> implements Algorithm<T> {
9+
@Override
10+
public List<T> findPath(Graph<T> graph, T source, T target) {
11+
final var queue = new LinkedList<T>();
12+
13+
final var visited = new HashSet<T>();
14+
final var previous = new HashMap<T, T>();
15+
16+
queue.add(source);
17+
18+
while (!queue.isEmpty()) {
19+
final var node = queue.pollFirst();
20+
if (target.equals(node)) {
21+
final var path = new LinkedList<T>();
22+
iterate(node, Objects::nonNull, previous::get).forEach(path::addFirst);
23+
return path;
24+
}
25+
visited.add(node);
26+
graph.nodes().get(node).keySet().stream()
27+
.filter(not(visited::contains))
28+
.forEach(it -> {
29+
previous.put(it, node);
30+
queue.add(it);
31+
});
32+
}
33+
return new LinkedList<>();
34+
}
35+
36+
}

src/main/java/algorithm/Dijkstras.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public List<T> findPath(Graph<T> graph, T source, T target) {
1212
final var distances = new HashMap<T, Double>();
1313
final var previous = new HashMap<T, T>();
1414
queue.add(source);
15+
distances.put(source, .0);
1516

1617
while (!queue.isEmpty()) {
1718
final var prev = queue.pollFirst();
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package algorithm
2+
3+
import spock.lang.Specification
4+
import spock.lang.Subject
5+
import spock.lang.Unroll
6+
7+
class BreadthFirstSearchSpec extends Specification {
8+
@Subject
9+
def algorithm = new BreadthFirstSearch()
10+
11+
@Unroll("from #source to #target the time is #time and the path is #expected")
12+
def 'should find a route for sample one'() {
13+
given:
14+
def graph = new Graph([
15+
A: [B: 7, C: 2],
16+
B: [A: 3, C: 5],
17+
C: [A: 1, B: 3]
18+
])
19+
20+
when:
21+
def path = algorithm.findPath(graph, source, target)
22+
23+
then:
24+
path == expected
25+
26+
and:
27+
graph.getDistance(path) == time as double
28+
29+
where:
30+
source | target || time | expected
31+
'A' | 'A' || 0 | ['A']
32+
'A' | 'B' || 7 | ['A', 'B']
33+
'B' | 'C' || 5 | ['B', 'C']
34+
}
35+
36+
}

0 commit comments

Comments
 (0)