-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
David Rupp
committed
May 13, 2017
1 parent
1de76ef
commit e1b343b
Showing
1 changed file
with
21 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,35 @@ | ||
(ns graffy.core) | ||
|
||
(defn add-edge [g s d] | ||
(-> g | ||
(assoc s (or (g s) (sorted-set))) | ||
(assoc d (or (g d) (sorted-set))) | ||
(update-in [s] conj d) | ||
(update-in [d] conj s))) | ||
(defn add-edge | ||
"graph: a map of sources to sets of dests; adds a bi-directional edge" | ||
[graph source dest] | ||
(-> graph | ||
(assoc source (or (graph source) (sorted-set))) | ||
(assoc dest (or (graph dest) (sorted-set))) | ||
(update-in [source] conj dest) | ||
(update-in [dest] conj source))) | ||
|
||
(defn vertices [g] | ||
(keys g)) | ||
(defn vertices [graph] | ||
(keys graph)) | ||
|
||
(defn neighbors [g n] | ||
(seq (or (g n) | ||
(defn neighbors [graph node] | ||
(seq (or (graph node) | ||
(sorted-set)))) | ||
|
||
(defn- traverse [g n strategy] | ||
(defn- traverse [graph node strategy] | ||
(assert (#{:bf :df} strategy) "Strategy must be one of :bf (breadth-first) or :df (depth-first)") | ||
(loop [acc [] stack (seq [n])] | ||
(loop [acc [] | ||
stack (seq [node])] | ||
(if (zero? (count stack)) | ||
acc | ||
(if (some #{(first stack)} acc) | ||
(recur acc (rest stack)) | ||
(if (= strategy :df) | ||
(recur (conj acc (first stack)) (concat (neighbors g (first stack)) (rest stack))) | ||
(recur (conj acc (first stack)) (concat (rest stack) (neighbors g (first stack))))))))) | ||
(recur (conj acc (first stack)) (concat (neighbors graph (first stack)) (rest stack))) | ||
(recur (conj acc (first stack)) (concat (rest stack) (neighbors graph (first stack))))))))) | ||
|
||
(defn dft [g n] | ||
(traverse g n :df)) | ||
(defn dft [graph node] | ||
(traverse graph node :df)) | ||
|
||
(defn bft [g n] | ||
(traverse g n :bf)) | ||
(defn bft [graph node] | ||
(traverse graph node :bf)) |