Skip to content

Commit d916583

Browse files
committed
remove the settled Set from shortestPathFrom()
1 parent 20a2428 commit d916583

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

mug/src/main/java/com/google/mu/util/graph/ShortestPath.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,22 +87,23 @@ public static <N> Stream<ShortestPath<N>> shortestPathsFrom(
8787
requireNonNull(findSuccessors);
8888
PriorityQueue<ShortestPath<N>> horizon =
8989
new PriorityQueue<>(comparingDouble(ShortestPath::distance));
90-
horizon.add(new ShortestPath<>(startNode));
91-
Map<N, ShortestPath<N>> seen = new HashMap<>();
92-
Set<N> settled = new HashSet<>();
90+
ShortestPath<N> root = new ShortestPath<>(startNode);
91+
Map<N, ShortestPath<N>> bestPaths = new HashMap<>();
92+
horizon.add(root);
93+
bestPaths.put(root.to(), root);
9394
return withSideEffect(
94-
whileNotNull(horizon::poll).filter(path -> settled.add(path.to())),
95+
whileNotNull(horizon::poll).filter(path -> bestPaths.get(path.to()) == path),
9596
path ->
9697
forEachPairOrNull(
9798
findSuccessors.apply(path.to()),
9899
(neighbor, distance) -> {
99100
requireNonNull(neighbor);
100101
checkNotNegative(distance, "distance");
101-
ShortestPath<?> old = seen.get(neighbor);
102+
ShortestPath<?> old = bestPaths.get(neighbor);
102103
if (old == null || path.distance() + distance < old.distance()) {
103104
ShortestPath<N> shorter = path.extendTo(neighbor, distance);
104-
seen.put(neighbor, shorter);
105105
horizon.add(shorter);
106+
bestPaths.put(neighbor, shorter);
106107
}
107108
}));
108109
}

0 commit comments

Comments
 (0)