用clojure写的depth first search算法

抱歉没时间写注释了……这个程序的目的是用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)))))))



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值