Skip to content

Instantly share code, notes, and snippets.

@gdevanla
Created February 2, 2014 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdevanla/8761497 to your computer and use it in GitHub Desktop.
Save gdevanla/8761497 to your computer and use it in GitHub Desktop.
;;Computes all possible paths through a graph (DAG)
;;assumes the graph is a DAG
;; Clojure
(defn all-paths [g]
(let [walk (fn walk [g seen n]
(cond
(empty? (g n)) seen
:else (mapcat (fn [m]
(walk g (conj seen m) m)) (g n))))]
(walk g [:u1] :u1)))
;;example
(all-paths {:u1 [:u2 :u3] :u2 [:u4] :u3 [:u4 :u6] :u4 [:u5] :u6 [:u5 :u7]})
;;(:u1 :u2 :u4 :u5 :u1 :u3 :u4 :u5 :u1 :u3 :u6 :u5 :u1 :u3 :u6 :u7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment