如果你有生成器(或协程,或续延),那么这可以通过递归简单地实现。在Python中:
def find_cycles_recursive(graph, L, cycle):
successors = graph[cycle[-1]]
if len(cycle) == L:
if cycle[0] in successors:
yield cycle
elif len(cycle) < L:
for v in successors:
if v in cycle:
continue
yield from find_cycles_recursive(graph, L, cycle + [v])
def find_cycles(graph, L):
for v in graph:
yield from find_cycles_recursive(graph, L, [v])
print(list(find_cycles({0: {1, 2}, 1: {0, 2, 3}, 2: {0, 1, 3}, 3: {1, 2}}, 3)))
您可以通过将条件中的
v in cycle
更改为
v <= cycle[0] or v in cycle
来进行优化。对于无向图,您还可以在结尾处过滤掉
cycle[1] > cycle[-1]
的图形。
如果您正在使用控制流程简陋的语言,则需要使用数据结构来模拟缺失的控制流程。在这里,这相当于保持迭代器的堆栈。(一般来说,您需要“解函数化延续”)。
def find_cycles2(graph, L):
for v, neighbors in graph.items():
cycle = [v]
stack = [iter(neighbors)]
while stack:
try:
if len(cycle) == L:
if cycle[0] in graph[cycle[-1]]:
print(cycle)
del cycle[-1]
del stack[-1]
elif len(cycle) < L:
v = next(stack[-1])
if v <= cycle[0] or v in cycle:
continue
cycle.append(v)
stack.append(iter(graph[v]))
except StopIteration:
del cycle[-1]
del stack[-1]
find_cycles2({0: {1, 2}, 1: {0, 2, 3}, 2: {0, 1, 3}, 3: {1, 2}}, 3)