Rudolf Adamkovič Personal site


Practice implementation

A clean-room implementation 11 of BFS in Elisp:

(defun my-breadth-first-graph-search (frontier neighbors goalp)
  "Perform depth-first search (DFS) on a graph.

All arguments are like those for `my-graph-search', which see."
  (let ((fifo #'nconc))
    (my-graph-search frontier neighbors goalp fifo)))
(defalias 'my-bfs-graph-search #'my-breadth-first-graph-search)

Test.

graph {
  bgcolor = transparent
  node [shape = circle]
  A B C D E F G I J K L
  F [style = filled] # goal
  A -- B
  A -- C
  A -- D
  B -- E
  B -- I
  C -- F
  D -- G
  D -- L
  E -- I
  E -- J
  G -- K
  G -- L
}
(let ((graph '((a b c d)
               (b a e i)
               (c a f)
               (d a g l)
               (e b i j)
               (f c)
               (g d k l)
               (i b e)
               (j e)
               (k g)
               (l d g)))
      (my-graph-search-debug t))
  (princ (format "Solution: %s\n"
                 (my-dfs-graph-search
                  '((a))
                  (lambda (path) (alist-get (car path) graph))
                  (lambda (path) (eq (car path) 'f))))))
Search: (a)
Search: (b a)
Search: (e b a)
Search: (j e b a)
Search: (i b a)
Search: (c a)
Search: (f c a)
Solution: (f c a)

Footnotes

(11)

Based on the implementation of the generic search, which see.


© 2025 Rudolf Adamkovič under GNU General Public License version 3.
Made with Emacs and secret alien technologies of yesteryear.