python - 从用户那里获取图形输入,用于 dfs 算法
问题描述
我想编写一个 DFS 算法,它可以为我在输入询问时给出的任何图形提供 DFS 结果。
但我找不到解决方案。我唯一发现的是代码中特定图形的算法。
# Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')
解决方案
这是工作代码,您可以更改图表或输入自己的代码。此 DFS 适用于加权路径。图形表示如下:
adjacency_list = {
'A': [('B', 1)],
'B': [('A', 1), ('C', 1)],
'C': [('A', 1)]
}
输入图形输入结,然后在数组中输入元组作为邻居(使用一些字符或数字停止输入该结)这是DFS
class Graph:
def __init__(self, adjacency_list):
self.adjacency_list = adjacency_list
def __str__(self):
return str(self.adjacency_list)
def get_neighbors(self, v):
return self.adjacency_list[v]
def dfs(self, start, stop):
visited = set([])
visited.add(start)
path = [start]
while len(path) > 0:
n = path[-1]
if n == stop:
print('Path found: {}'.format(path))
return path
has_unvisited = False
for (m, weight) in self.get_neighbors(n):
if m not in visited:
path.append(m)
visited.add(m)
has_unvisited = True
break
if (not has_unvisited):
path.pop()
print('Path doesnt exist')
return None
你用这个来调用 DFS:
g = Graph(adjacency_list)
g.dfs('A','C')
推荐阅读
- javascript - 我如何处理 echarts 工具提示格式化程序中的点击事件女巫反应?
- wordpress - 如何在wordpress中为每个用户生成主页的随机链接并仅在单击链接时显示内容?
- django - NoReverseMatch 与通用 DeleteView
- google-cloud-platform - Google Cloud Functions 的“一劳永逸”
- reactjs - 想要在 Reactjs 中的数组中并作为道具传递的字符串中提供超链接
- docker - 为什么文件夹没有绑定?
- javascript - JQuery autcomplete在对话框中不起作用
- python - python共享字典使用ray?
- r - 比较 R 中的浮点数
- performance - Metal Shader 指针或本地复制性能