白話說DFS&BFS這兩種算法主要解決迷宮問題、路徑搜索等方面具有廣泛的應用~
圖形搜索演算法是用於在圖形(Graph)中尋找特定節點或遍歷整個圖形的算法。圖形是由節點(或稱為頂點)和之間的邊組成的數學結構
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for neighbor in graph[start] - visited:
dfs(graph, neighbor, visited)
return visited
# Example usage
graph = {'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}}
dfs(graph, 'A')
基本思想是從起始節點開始,依次探索與起始節點距離為 1、2、3... 的節點,直到找到目標節點或所有節點都被探索完為止。使用佇列(Queue)來實現 DAY 3 「陣列(Array)、連結串列(Linked List) VS. 堆疊(Stack)、佇列(Queue)」還有Python資料結構傻傻分不清楚?
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
# 使用示例
graph = {'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']}
bfs(graph, 'A')