File tree Expand file tree Collapse file tree 2 files changed +38
-1
lines changed Expand file tree Collapse file tree 2 files changed +38
-1
lines changed Original file line number Diff line number Diff line change 33import java .util .List ;
44
55public interface Algorithm <T > {
6- List <T > findRoute (Graph <T > graph , T source , T target );
6+ List <T > findPath (Graph <T > graph , T source , T target );
77}
Original file line number Diff line number Diff line change 1+ package algorithm ;
2+
3+ import java .util .*;
4+ import java .util .stream .Stream ;
5+
6+ public class Dijkstras <T > implements Algorithm <T > {
7+
8+ @ Override
9+ public List <T > findPath (Graph <T > graph , T source , T target ) {
10+ final var queue = new LinkedList <T >();
11+ final var visited = new HashSet <T >();
12+ final var distances = new HashMap <T , Double >();
13+ final var path = new HashMap <T , T >();
14+ queue .add (source );
15+
16+ while (!queue .isEmpty ()) {
17+ final var previous = queue .pollFirst ();
18+ final var edges = graph .get (previous );
19+ edges .forEach ((node , time ) -> {
20+ final var distance = distances .getOrDefault (previous , .0 ) + time .doubleValue ();
21+ if (!visited .contains (node )) {
22+ queue .add (node );
23+ visited .add (node );
24+ }
25+ if (distance < distances .getOrDefault (node , Double .MAX_VALUE )) {
26+ path .put (node , previous );
27+ distances .put (node , distance );
28+ }
29+ });
30+ }
31+
32+ final var route = new LinkedList <T >();
33+ Stream .iterate (target , Objects ::nonNull , path ::get ).forEach (route ::addFirst );
34+ return route ;
35+ }
36+
37+ }
You can’t perform that action at this time.
0 commit comments