Scheme Find all possible paths for an undirected graph

╄→гoц情女王★ 提交于 2019-12-13 02:19:51

问题


I am having problem to print out all the possible paths. Currently I am only able to print out one path, and if (path-demo "J" "I"), the program will shown this error mcdr: expects argument of type <mutable-pair>; given #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")

回答1:


In your definition of net you have forgotten to list the nodes to which H is connected.

When the error occurs node and net have the following values:

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)))

Thus

(assoc node net))

will return #f because H has no associations in net. And this leads to the error from cdr:

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



回答2:


It is likely that the following returns #f:

(cdr (assoc node net))

Regarding comment (for formatting):

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


来源:https://stackoverflow.com/questions/7805005/scheme-find-all-possible-paths-for-an-undirected-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!