Skip to content

Instantly share code, notes, and snippets.

@skatenerd
Last active January 2, 2016 23:39
Show Gist options
  • Save skatenerd/8378189 to your computer and use it in GitHub Desktop.
Save skatenerd/8378189 to your computer and use it in GitHub Desktop.
dfs without repetition through a graph
(def grapph {
;some stuff
})
(defn neighbors [node]
(get graph node))
(defn dft [node visited-so-far]
(let [new-visited-so-far (set (conj visited-so-far node))
unvisited-children (set (remove visited-so-far (set (neighbors node))))
results-from-children (reduce
(fn [state child]
(let [visit-from-child (dft child (:visited-so-far state))]
{:visited-so-far (clojure.set/union (:visited-so-far state) (:visited-so-far visit-from-child))
:node-sequence (concat (:node-sequence state) (:node-sequence visit-from-child))}))
{:visited-so-far new-visited-so-far
:node-sequence []}
unvisited-children)]
{:node-sequence (cons node (:node-sequence results-from-children))
:visited-so-far (clojure.set/union new-visited-so-far (:visited-so-far results-from-children))}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment