Scheme查找无向图的所有可能路径

时间:2011-10-18 09:19:38

标签: graph scheme racket breadth-first-search

打印出所有可能的路径时遇到问题。目前我只能打印出一个路径,如果(path-demo“J”“I”),程序将显示此错误mcdr:期望类型<mutable-pair>的参数;给定#f

 (define net
  '(("A" "B")
    ("B" "A" "C")
    ("C" "B" "D")
    ("D" "C" "E" "F")
    ("F" "I" "D")
    ("I" "F")
    ("E" "D" "J")
    ("J" "E" "G")
    ("G" "J" "H"))) 

 (define (path-demo start finish)
         (for-each (lambda (x) (display x) (display " "))
                   (cons "Route:" (shortest-path start finish net))))

 (define (shortest-path start end net)
    (bfs end (list (list start)) net))

 ;; Breadth-first search
  (define (bfs end queue net)
    (display queue) (newline) (newline) ; entertainment
    (if (null? queue)
      '()
      (let ((path (car queue)))
       (let ((node (car path)))
         (if (equal? node end) ;; Graham used CL eql
             (reverse path)
             (bfs end 
                  (append (cdr queue)
                          (new-paths path node net))
                  net))))))

 (define (new-paths path node net)
   (map (lambda (n) (cons n path)) (cdr (assoc node net))))

;;
(path-demo "J" "I")

2 个答案:

答案 0 :(得分:1)

在您对net的定义中,您忘记列出H所连接的节点。

当错误发生时,node和net具有以下值:

node: H 
net: ((A B) (B A C) (C B D) (D C E F) (F I D) (I F) (E D J) 
      (J E G) (G J H)))

因此

(assoc node net))

将返回#f,因为H在网络中没有关联。 这导致了cdr的错误:

cdr: expects argument of type <pair>; given #f

答案 1 :(得分:0)

以下内容可能会返回#f

(cdr (assoc node net))

关于评论(格式化):

(define (new-paths path node net)
   (write node)
   (newline)
   (map (lambda (n) (cons n path)) (cdr (assoc node net))))