抱歉没时间写注释了……这个程序的目的是用depth first search的方法找出一个graph中从某个节点到某个节点的路径
因为没有写注释,所以有什么关于代码的问题可以给我留言,我一定回复。
(ns depthfirst)
(def my-graph '((a b) (a c) (b c) (b d) (c e) (e f) (f g) (d g) (g h)))
(defn member?
"Test if an atom is a element of a list"
[x l]
(if (empty? l)
false
(if (= x (first l))
true
(member? x (rest l)))))
(defn find-neighbour
"Find the possible neighbour"
[graph path node acc]
(if (empty? graph)
acc
(if (and (= node (first (first graph))) (not (member? (nth (first graph) 1) path)))
(find-neighbour (rest graph) path node (cons (cons (nth (first graph) 1) path) acc))
(find-neighbour (rest graph) path node acc))))
(defn find-path
"Perform a depth first search to find a possible path in a node graph"
[graph start goal]
(loop [queue (cons (cons start '()) '())]
(if (empty? (first queue))
nil
(if (member? goal (first queue))
(reverse (first queue))
(recur (concat (find-neighbour graph (first queue) (first (first queue)) '()) (rest queue)))))))