我有一个二分加权图(更确切地说是一个分配问题),我想找到最便宜的路径/选择。知道如何实现DFS或Greedy BFS来实现这条路径吗?
我将图表表示为一个adiacency列表(或者我认为最好),就像这样和DFS算法
adjlist = {"A": ["W", "X"],
"B": ["W", "X", "Y", "Z"],
"C": ["Y", "Z"],
"D": ["W", "X", "Y", "Z"],
"W": ["A", "B", "D"],
"X": ["A", "B", "D"],
"Y": ["B", "C", "D"],
"Z": ["B", "C", "D"] }
def dfser(graph, root):
visited =[]
stack = [root, ]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
stack.extend([x for x in graph[node] if x not in visited])
return visited
我想要的可能吗?结果必须是:AWBXCYDZ或最便宜的东西。
或者我可以从root获得所有可能的遍历吗?这个DFS只给我一个,但我想要所有可能的转换
答案 0 :(得分:0)
使用dijkstra或A*算法可以查找最便宜的路径。 Networkx为该任务提供full API。
networkx模块实现bipartite graphs及相关算法:
Dicti = {"A": {"W": 2, "X": 2},
"B": {"W": 4, "X": 3, "Y": 2, "Z": 5},
"C": {"Y": 2, "Z": 2},
"D": {"W": 5, "X": 5, "Y": 4, "Z": 3},
"W": {"A": 2, "B": 4, "D": 5},
"X": {"A": 2, "B": 3, "D": 5},
"Y": {"B": 2, "C": 2, "D": 4},
"Z": {"B": 5, "C": 2, "D": 3}
}
graph = nx.Graph()
for node, succs in Dicti.items():
for succ, weight in succs:
graph.add_edge(node, succ, weight=weight)
print(nx.dijkstra_path(graph, 'A', 'Z')) # here is Dijkstra