【发布时间】:2016-07-13 03:49:10
【问题描述】:
我正在尝试定义一个 topological-sort 函数来生成图形拓扑排序的所有可能排序:
(define (topological-sort graph)
(if (null? graph)
`()
(map (lambda (x)
(cons x
(topological-sort (reduce x graph))))
(no-in-edge graph))))
只获取一棵树(多层列表)
'((a
(b
(c
(e
(d (f))
(f (d))))
(e
(c
(d (f))
(f (d)))
(d
(c
(f)))))
(e
(b
(c
(d (f))
(f (d)))
(d
(c (f))))
(d
(b
(c
(f)))))))
如何将树扁平化为列表列表?
a, b, c, e, f, d
a, e, b, c, f, d
a, b, e, c, f, d
a, e, d, b, c, f
a, e, b, d, c, f
a, b, e, d, c, f
a, b, c, e, d, f
a, e, b, c, d, f
a, b, e, c, d, f
我尝试了几个旅行功能,但都失败了。
总节目:
(define (no-in-edge graph)
(filter (lambda (x)
(and (element x
(vertex graph))
(not (element x
(out-vertex graph)))))
(vertex graph)))
(define (reduce x graph)
(if (null? graph)
`()
(if (eq? x (caar graph))
(reduce x
(cdr graph))
(cons (car graph)
(reduce x (cdr graph))))))
(define (element x list)
(if (null? list)
#f
(if (eq? x (car list))
#t
(element x (cdr list)))))
(define (vertex graph)
(map car graph))
(define (out-vertex graph)
(remove-duplicates (apply append
(map cdr graph))))
(define (top-level graph)
(apply append (topological-sort graph)))
(define (topological-sort graph)
(if (null? graph)
`()
(map (lambda (x)
(cons x
(topological-sort (reduce x graph))))
(no-in-edge graph))))
(define test-graph `((a b c e)
(b c)
(c f)
(e d f)
(d)
(f)))
(topological-sort test-graph)
【问题讨论】:
-
它是否列出了所有通往您想要的叶子的路径?
-
@AlexKnauth 完全正确。
标签: algorithm tree scheme racket