如果我理解正确,那么问题是什么时候可以到达起点。为了简单和明确起见,我将从一个普通的 python 开始。明显的蛮力解决方案是检查数据中呈现的每个来源的所有可能目的地。当然,您需要稍微组织一下您的数据。然后它只是一个链接。下面的代码实现了这种方法。
def get_all_sources(data):
ans = dict()
for src, dst in data:
ans.setdefault(src, set()).add(dst)
return ans
def get_all_possible_destinations(src, all_src, ans=None):
ans = set() if ans is None else ans
for dst in all_src.get(src, set()):
if dst in ans:
continue
ans.add(dst)
get_all_possible_destinations(dst, all_src, ans)
return ans
def pipeline_source_by_source(data):
all_src = get_all_sources(data)
for src in all_src:
all_possible_destiations = get_all_possible_destinations(src, all_src)
if src in all_possible_destiations:
print(f"found problem: {src} -> {src}")
break
else:
print('no problems found')
if __name__ == '__main__':
data_list = [
[(1, 2)],
[(1, 2), (2, 3)],
[(1, 2), (3, 4), (2, 3)],
[(1, 2), (3, 4), (2, 3), (3, 1)],
[(5, 6), (5, 7), (5, 8), (5, 9), (9, 10), (10, 5)],
[(5, 6), (5, 7), (5, 8), (5, 9), (9, 10), (10, 15)]
]
for idx, data in enumerate(data_list):
print(idx)
pipeline_source_by_source(data)
结果:
0
no problems found
1
no problems found
2
no problems found
3
found problem: 1 -> 1
4
found problem: 5 -> 5
5
no problems found