DFS BFS Graph python
DFS BFS Graph python
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E'],
'D': [],
'E': []
}
DFS
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
# Usage
print("DFS traversal:")
dfs(graph, 'A')
BFS(breadth)
from collections import deque
while queue:
node = queue.popleft()
if node not in visited:
print(node, end=' ')
visited.add(node)
queue.extend(graph[node])
# Usage
print("\nBFS traversal:")
bfs(graph, 'A')
Best first
import heapq
while pq:
_, node = heapq.heappop(pq)
if node not in visited:
print(node, end=' ')
visited.add(node)
if node == goal:
break
for neighbor in graph[node]:
if neighbor not in visited:
heapq.heappush(pq, (heuristic[neighbor], neighbor))
# Usage
print("\nBest-First Search (Greedy):")
best_first_search(graph, 'A', 'E')
A*
def a_star(graph, start, goal, heuristic):
open_set = [(heuristic[start], 0, start)]
visited = set()
while open_set:
f, g, current = heapq.heappop(open_set)
if current in visited:
continue
print(current, end=' ')
visited.add(current)
if current == goal:
break
# Usage
print("\nA* Search:")
a_star(graph, 'A', 'E', heuristic)