【问题标题】:Hamiltonian path function returns empty path unexpectedly哈密​​顿路径函数意外返回空路径
【发布时间】:2023-03-08 23:38:01
【问题描述】:

我正在努力解决的任务是基于一个名为骑士之旅的问题和这个 Numberphile 视频:https://www.youtube.com/watch?v=G1m7goLCJDY

基本上,我在这里要做的是编写一个辅助函数,它递归地计算给定图(V,E)中的哈密顿路径。它应该按该路径的顺序返回 V 中的元素列表,如果不存在这样的路径,则返回 nil 。但它只返回路径 P 的空列表。

到目前为止我的尝试(进一步向下):(格式有点奇怪)

(defn- H'
;; 
;;     "This is the helper function for computing the Hamiltonian path. 
;;      E is the relation, i.e. the graph, we are looking for a path in.
;;      a is the current node.
;;      S is the set of nodes we haven't visited yet.
;;      P is the path we have traveled so far.
;;      
;;      H' should return a Hamiltonian path through E
;;      that begins with P, then goes through a, and then visits every vertex 
;;      in the set S.
;;      If no such path exists, it should return nil."
;; 
    [E a S P]
;;     
 { 
 :pre [
         (not (contains? S a))
         (not (contains? (set P) a))
         (empty? (intersection S (set P)))
     ]
 :post [
         (or (empty? %) (= (set %) (union S (set P) #{a})))
         (or (empty? %) (= (count %) (+ (count S) (count P) 1)))
       ]
 }

;; (image-of E a) returns the set of edges leading away from the current vertex 

;;     MY ATTEMPT:
    (if-not (empty? S)
        (if (some #(H' E % (disj S %) P) (intersection (image-of E a) S))
            (concat P [a])
        )
    )

)
(defn H
   "compute a Hamiltonian path in the graph (V, E); returns a list of the elements in V in the
   order of that path, or nil if no such path exists"

 [V E]

     (some #(H' E % (disj V %) '()) V)
)

我不明白为什么我没有从 H 那里得到任何路径 P 作为回报,只是一个空列表?我是否在错误的条件或类似的情况下终止递归? some-function 的谓词是否表述错误?

如果需要进一步说明或需要更多代码,请告诉我。

【问题讨论】:

  • 你不应该在你的函数名中使用单引号'。删除它并重试,然后更新您的问题。另请参阅此模板项目中的文档资源列表(可能会将您的代码放入现有文件中以尝试运行它):github.com/io-tupelo/clj-template#documentation
  • 嗯?这个函数有很多问题,但它的名字不是其中之一。
  • 该名称是分配中代码框架的一部分,它可以工作并且可以运行。我只是在这里发布了 sn-ps,因为我不想发布代码墙。

标签: math clojure knights-tour


【解决方案1】:

怎么了?

剥离到最低限度,

(defn- H' [E a S P]
  (if (seq S)
    (if (some #(H' E % (disj S %) P) (intersection (image-of E a) S))
      (concat P [a]))))

...其中(if-not (empty? S) ... ) 被简化为(if (seq S) ... )

考虑 nS 中的元素数量。

  • 如果 n 为零,H' 返回nil
  • 如果 n 是肯定的,则结果是 H' 调用的 or-ing,其中 S 的元素个数是n-1

induction 遵循H' 为所有S 返回nil

用唐克努特的话来说,“我没有尝试过。我只是证明了它。”

说得对

(H' E a S P) 应该返回从a 开始通过顶点S 的哈密顿路径。上面的函数通过S计算出这样一条路径:

(some #(H' E % (disj S %) P) (intersection (image-of E a) S))

...然后扔掉它。

我们要做的就是在前面加上a 以保持归纳承诺:

(defn- H' [E a S P]
  (if (seq S)
    (let [tail (some #(H' E % (disj S %) P) (intersection (image-of E a) S))]
      (and tail (cons a tail)))
    (list a)))

...and 负责解决找不到路径的问题。

注意...

  • 这个我没试过。
  • 我尝试过有更好的表达方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2014-12-20
    • 2011-11-12
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多