0% found this document useful (0 votes)
9 views2 pages

TD 06

Uploaded by

eyaallaoui914
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

TD 06

Uploaded by

eyaallaoui914
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Td 06 :

Exercice01:

1)
from collections import deque

# Parcours en largeur (BFS)


def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
queue.extend([n for n in graph[node] if n not in visited])
return visited

# Parcours en profondeur (DFS)


def dfs(graph, start):
visited = set()
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
stack.extend([n for n in graph[node] if n not in visited])
return visited

2)

def bfs_all(graph):
visited = set()
for start in graph:
if start not in visited:
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
queue.extend([n for n in graph[node] if n not in visited])
return visited

def dfs_all(graph):
visited = set()
for start in graph:
if start not in visited:
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
stack.extend([n for n in graph[node] if n not in visited])
return visited
3)

def bfs_shortest_path(graph, start, goal):


queue = deque([(start, [start])])
while queue:
node, path = queue.popleft()
if node == goal:
return path
for neighbor in graph[node]:
if neighbor not in path:
queue.append((neighbor, path + [neighbor]))
return None

4)

def bfs_with_predecessor(graph, start):


visited = set()
queue = deque([start])
predecessor = {start: None}
while queue:
node = queue.popleft()
if node not in visited:
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited and neighbor not in predecessor:
predecessor[neighbor] = node
queue.append(neighbor)
return predecessor

5)

def shortest_path(graph, start, goal):


predecessor = bfs_with_predecessor(graph, start)
path = []
node = goal
while node is not None:
path.append(node)
node = predecessor[node]
return path[::-1] if path[-1] == start else None

You might also like