這是我的python代碼:
# Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C','D'],
'B' : ['E', 'F'],
'C' : ['G'],
'E' : [],
'F' : [],
'G' : ['K','H'],
'K' : [],
'H' : [],
'D' : [],
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
break
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, 'A')
它是關于深度優先搜索演算法的,當我在沒有 break 陳述句的情況下編譯它時,結果將是:A B E F C G K H D
當我放置 break 陳述句時,結果將是:A B E,我的問題是我如何在這里停止這個演算法在像 F 這樣的特定節點,所以結果就像
A B E F
我試圖在第 23 行之后放置 break 但它只是給了我這個結果 A B E 但我希望 F 包含在其中
uj5u.com熱心網友回復:
為了停止回圈,如果找到您正在搜索的節點,我們希望回傳一些內容:
# Using a Python dictionary to act as an adjacency list
graph = {
'A': ['B', 'C', 'D'],
'B': ['E', 'F'],
'C': ['G'],
'E': [],
'F': [],
'G': ['K', 'H'],
'K': [],
'H': [],
'D': [],
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node, stop_at): # function for dfs
if node not in visited:
print(node)
# We check if the current node is the one for which we are looking for
if node == stop_at:
return True
visited.add(node)
for neighbour in graph[node]:
# If we found the node, we break out from the loop
if dfs(visited, graph, neighbour, stop_at):
return True
# If we did not find the node we were looking for, we return False
return False
# Driver Code
if __name__ == "__main__":
print("Following is the Depth-First Search")
dfs(visited, graph, 'A', 'F')
在 的情況下dfs(visited, graph, 'A', 'F'),它應該列印:
A
B
E
F
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400224.html
上一篇:索引錯誤:索引X超出軸0的范圍,大小為Y(Python)
下一篇:元組串列的所有可能組合
