Skip to content

Instantly share code, notes, and snippets.

@Netpilgrim
Created August 28, 2011 14:18
Show Gist options
  • Save Netpilgrim/1176716 to your computer and use it in GitHub Desktop.
Save Netpilgrim/1176716 to your computer and use it in GitHub Desktop.
DFS path finder
(defn find-path
[graph from to]
((fn this [graph from to path]
(if (= from to)
(println "Found it:" path)
(let [children (for [v (graph from) :when (not (some #{v} path))] v)]
(if (empty? children)
(println "Dead end:" path)
(doseq [v children]
(this graph v to (conj path v)))))))
graph from to [from]))
(def graph {:a [:b :c :g]
:b [:e :g]
:c []
:d []
:e [:a]
:f [:c :d]
:g [:e]})
(find-path graph :a :e)
;; Output:
;; Found it: [:a :b :e]
;; Found it: [:a :b :g :e]
;; Dead end: [:a :c]
;; Found it: [:a :g :e]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment