简体   繁体   English

在Clojure中遍历图

[英]Traversing a graph in clojure

Hope you are well. 希望你很好。 I am stuck with a recursive program that is suppose to traverse a graph until it finds a path back to the start node. 我受困于一个递归程序,该程序应该遍历图,直到找到返回起始节点的路径。 the code is here, 代码在这里,

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

there is something wrong with the way I accumulate the result I couldnt find what exactly. 我累积结果的方式有问题,我找不到确切的结果。

The function should return something like '(CDC CEBC) for the above call. 该函数应为上述调用返回类似'(CDC CEBC)的内容。

This did the trick, hope its helpful for someone :) 这可以解决问题,希望它对某人有用:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM