Skip to content

Instantly share code, notes, and snippets.

@ummels
Last active March 27, 2024 07:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ummels/86c09182dee25b142280 to your computer and use it in GitHub Desktop.
Save ummels/86c09182dee25b142280 to your computer and use it in GitHub Desktop.
Dijsktra's shortest-path algorithm in Clojure
(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