Skip to content

Commit

Permalink
Add a method to return all-paths through a graph
Browse files Browse the repository at this point in the history
  • Loading branch information
eschulte committed Apr 14, 2020
1 parent d2d282e commit dba5223
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
15 changes: 15 additions & 0 deletions graph.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@
:closedp
:clustering-coefficient
:cliques
;; All paths
:all-paths
;; Shortest Path
:shortest-path
;; Max Flow
Expand Down Expand Up @@ -1053,6 +1055,19 @@ The Bron-Kerbosh algorithm is used."))
(bron-kerbosch nil (nodes graph) nil))
cliques)

(defgeneric all-paths (graph a b)
(:documentation "Return all paths in GRAPH from A to B.")
(:method ((graph graph) a b)
(labels
((step-path (from to visited)
(if (equal from to)
(list (list to))
(mapcar {cons from}
(mappend {step-path _ to (cons from visited)}
(set-difference (neighbors graph from)
visited))))))
(step-path a b nil))))


;;; Shortest Path
(defgeneric shortest-path (graph a b &optional heuristic)
Expand Down
6 changes: 6 additions & 0 deletions test.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,12 @@
'((:Q :S :R) (:C :S) (:A :C :B))
:test #'set-equal))))

(deftest all-path-between-foo-and-baz-or-qux ()
(with-fixture normal-graph
(is (set-equal (all-paths *graph* 'a 'f)
'((a b c d e f) (a b c e f) (a b f))
:test #'equalp))))

(deftest shortest-path-between-foo-and-baz-or-qux ()
(with-fixture less-small-graph
(is (tree-equal (shortest-path (digraph-of *graph*) :foo :baz)
Expand Down

0 comments on commit dba5223

Please sign in to comment.