Python implementation of the width path in graphs (BFS)

This article follows the one on the BFS algorithm here: http://128mots.com/index.php/2020/02/11/parcours-en-largeur-dans-les-graphes-bfs/

The Python implementation of this algorithm is as follows:

from collections import deque

def bfs (graph, vertex):
    tail - deque([vertex])
    distance ' vertex: 0'
    father ' vertex: None'
    while tail:
    	t - tail.popleft()
    	for neighbor in grap[t]h:
    		If neighbor not in distance:
    			tail.append (neighbour)
    			distance[voisin] - distance[t] - 1
    			fathe[voisin]r 't'
    return distance, father


graph ajacence #Liste
graph
	'A': ['B','C'],
	'B': ['A','C', 'D'],
	'C': ['D'],
	'D':['C','A']
}

distance, pere - bfs (graph,'A')
print ("Distances" - str (distance))
print ("Pere " - str (father))

Auteur / autrice

Retour en haut