Finding path between 2 points in Racket

前端 未结 2 1913
天命终不由人
天命终不由人 2020-12-21 18:48

I have following list of connections:

(define routelist
  (list
      (list\'a \'b)
      (list\'a \'c)
      (list\'b \'e)
      (list\'b \'f)
      (list\         


        
相关标签:
2条回答
  • 2020-12-21 19:23

    Here is a very simple solution:

    (define (mainpath routelist start end)
      (define (neighbors node)
        (map second (filter (lambda (x) (eq? (first x) node)) routelist)))
      (define (visit node visited)
        (when (not (member node visited))
          (when (eq? node end)
            (println (reverse (cons node visited))))
          (let ((new-visited (cons node visited)))
            (map (lambda (x) (visit x new-visited)) (neighbors node)))))
      (visit start '())
      "No more paths")
    

    This recursive function, that can manage also graphs with loops, keeps a list of nodes already visited along the current path and stops when it has visited all the nodes reachable from the start node. When the current node is the end node, the current path is printed.

    0 讨论(0)
  • 2020-12-21 19:36

    Use DFS algorithm will be ok.

    (define (mainpath routelist start end)
      (letrec ([next-nodes (λ (node)
                            (for/list ([al routelist]
                                       #:when (eq? node (first al)))
                                      (second al)))]
               [path (λ (node vlist)
                       (let ([new-list (cons node vlist)])
                         (when (eq? node end)
                           (println (reverse new-list)))
                         (for ([next (next-nodes node)]
                               #:unless (memq next vlist))
                              (path next new-list))))])
        (path start '())))
    
    0 讨论(0)
提交回复
热议问题