【发布时间】:2019-09-17 02:08:08
【问题描述】:
我有一个 X 点和 Y 点的列表,这些点将被导入到程序中。我想知道是否可以为如何连接它们创建一个目录?几乎就像一个树形图,但不是使用边缘,而是使用 x 和 y 点。
示例中的[0] 将是起点,数字将是导入文件中的点。
举例
----4------5
|
8------7-----6----[0]------1-------2-----3
|
9---
我发现了一种名为Breadth-first search 的算法,如果给定起点和终点,它能够确定最佳路径。我知道该算法用于搜索可能的路径但不确定路径。如果给出上面示例中的要点..
point X Y
0 0 0
1 1 0
2 2 0
3 3 0
4 1.5 0.5
5 2.5 0.5
6 -1 0
7 -2 0
8 -3 0
9 -2.5 -0.5
我希望以上几点能够生成一个类似..的目录
graph = {
'0': ['1', '6'],
'1': ['2', '4'],
'2': ['3'],
'4': ['5'],
'6': ['7'],
'7': ['8','9']
}
我为Breadth-first Search 找到了一个很好的例子here,但它需要已经创建的目录结构。感谢您提供任何帮助或建议。
广度优先搜索.py
def bfs(graph, start, end):
queue = []
queue.append([start])
while queue:
path = queue.pop(0)
node = path[-1]
if node == end:
return path
for adjacent in graph.get(node, []):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print(bfs(graph, '0', '5'))
【问题讨论】:
标签: python python-3.x tree graph-theory shortest-path