Skip to content

Instantly share code, notes, and snippets.

@Netpilgrim
Created August 19, 2011 20:58
Show Gist options
  • Save Netpilgrim/1157986 to your computer and use it in GitHub Desktop.
Save Netpilgrim/1157986 to your computer and use it in GitHub Desktop.
Depth first search
(defn dfs [g]
(let [visited (atom #{})]
(letfn
[(search_tree [v]
(if (not (@visited v))
(do
(swap! visited conj v)
(cons v (search (g v))))))
(search [vs]
(if (seq vs)
(mapcat search_tree vs)))]
(search (keys g)))))
;===============================================================================
(def graph {:a [:b :c :g]
:b [:e :g]
:c []
:d []
:e [:a]
:f [:c :d]
:g [:e]})
(def vertex_order [:a :b :e :g :c :d :f])
(assert (= (dfs graph) vertex_order))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment