Last active
March 27, 2024 07:33
-
-
Save ummels/86c09182dee25b142280 to your computer and use it in GitHub Desktop.
Dijsktra's shortest-path algorithm in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clojure.data.priority-map :refer [priority-map]]) | |
(defn map-vals [m f] | |
(into {} (for [[k v] m] [k (f v)]))) | |
(defn remove-keys [m pred] | |
(select-keys m (filter (complement pred) (keys m)))) | |
(defn dijkstra | |
"Computes single-source shortest path distances in a directed graph. | |
Given a node n, (f n) should return a map with the successors of n as keys | |
and their (non-negative) distance from n as vals. | |
Returns a map from nodes to their distance from start." | |
[start f] | |
(loop [q (priority-map start 0) r {}] | |
(if-let [[v d] (peek q)] | |
(let [dist (-> (f v) (remove-keys r) (map-vals (partial + d)))] | |
(recur (merge-with min (pop q) dist) (assoc r v d))) | |
r))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment