在 clojure 中遍历图形

Traversing a graph in clojure

希望你一切都好。我坚持使用一个递归程序,该程序应该遍历一个图,直到找到返回起始节点的路径。代码在这里,

(def graph {:A {:B 5 :D 5 :E 7}
            :B {:C 4}
            :C {:D 8 :E 2}
            :D {:C 8 :E 6}
            :E {:B 3}
            })

(defn looper [g startnode & args]  
  (let [[inode] (vec args)
        acc []]
    (if (= startnode inode)    
      (conj acc inode)    
      (conj acc inode (map (partial looper g startnode) (vec (keys (get g inode)))))
  )))


(looper graph :C)

我累积结果的方式有问题我找不到确切的内容。

对于上述调用,该函数应该return类似于'(CDC CEBC)。

成功了,希望对大家有帮助:)

(defn- dfs
  [graph goal]
  (fn search
    [path visited]
    (let [current (peek path)]
      (if (= goal current)
        [path]
        (->> current graph keys
             (remove visited)
             (mapcat #(search (conj path %) (conj visited %))))))))
(defn findpath
  "Returns a lazy sequence of all directed paths from start to goal
  within graph."
  [graph start goal]
  ((dfs graph goal) [start] #{start}))

(defn circular-path-count [graph node] 
  (flatten (map (fn [s]
       (map count (findpath graph s node))) (vec (keys (get-in graph [node]))) )))



e.g. usage: (circular-path-count paths :B)