Skip to content

Instantly share code, notes, and snippets.

@pr4v33n

pr4v33n/bfs.clj Secret

Created March 14, 2012 17: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 pr4v33n/ce8773ccc838f0a48100 to your computer and use it in GitHub Desktop.
Save pr4v33n/ce8773ccc838f0a48100 to your computer and use it in GitHub Desktop.
Breadth First Search
(def mygraph {:A {:B 85, :C 217, :E 173},
:B {:F 80},
:C {:G 186 :H 103},
:D {},
:E {:J 502},
:F {:I 250}
:G {},
:H {:D 183 :J 167}
:I {:J 84},
:J {}
})
(defn bfs [G s]
(defstruct node-info :color :distance :parent)
(def node-info-map (ref (reduce #(assoc %1 %2 (struct node-info "white" Integer/MAX_VALUE nil)) {} (keys G))))
(def Q (ref (conj clojure.lang.PersistentQueue/EMPTY s)))
(dosync (alter node-info-map assoc s (struct node-info "grey" 0 nil)))
(loop []
(when-not (empty? @Q)
(let [u (peek @Q)
adj (keys (G u))
du (get-in @node-info-map [u :distance])]
(dosync
(alter Q pop)
(doseq [v adj]
(if (= (get-in @node-info-map [v :color]) "white")
(do
(alter node-info-map assoc v (struct node-info "grey" (+ du 1) u))
(alter Q conj v))))
(alter node-info-map assoc-in [u :color] "black"))
(recur)))) @node-info-map)
(prn (bfs mygraph :C))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment