BFS: Breadth first search
2 min readDec 26, 2021
BFS searches for a variable in a table we give the code. Formatted like the binary tree, the BFS is a good way to search for a wanted variable.
HOW IT WORKS:
The BFS searches from the first parent: Derp. Afterwards, in this examples, it starts from the left to the right. So the order BFS will search in is: Derp, Derpina, Derpary, Derpo, Derpohn, Derpavid, then finally Derpammy.
EXAMPLE:
print("News report: Banana dealer on the loose.")print("Being a detective, you decided to go investigate.")def banana_dealer(name):if name == 'Banana':return Truedef search(name):global not_dealerdealer = []dealer += graph[name]while dealer:person = dealer.pop(0)if banana_dealer(person):print(person + ' is Banana dealer.')return Trueelse:not_dealer.append(person)dealer += graph[person]print('You dont find the banana dealer.')return Falsenot_dealer = []graph = {'Tom': ['Ivan', 'Ira', 'Kevin'],'Ivan':['Peter'],'Ira':['Banana'],'Kevin':['Mary'],'Peter':[],'Banana':[],'Mary':[]}search('Tom')print('Here is the list of searched people : ', not_dealer)
Here is the result:
A video I recorded to explain:
Screencastify share link: https://watch.screencastify.com/v/LL2Yhsp9e7SEUToPOhH6
Youtube: