algos_and_structures/grokaem/graphs/bfs.py
2024-11-02 14:03:30 +03:00

50 lines
1.4 KiB
Python

from collections import deque
# Dummy function to check that person is selling mangos
def person_is_seller(name: str) -> bool:
# If last person letter is "m" than he is mango seller
return name[-1] == "m"
# Implementation of BFS of example graph
def bfs():
# Modeling graph using hash map
graph = {}
graph["me"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["tom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["tom"] = []
graph["jonny"] = []
# Creating queue for checking
search_queue = deque()
# Declaring searched persons list for avoiding infinite loop situation
searched = []
# Adding first people to queue, starting from me
search_queue += graph["me"]
# Start searching
while search_queue:
# Getting first person from queue
person = search_queue.popleft()
# Checking that person is already searched
if person not in searched:
if person_is_seller(person):
print("{name} is a mago seller!".format(name=person))
return
else:
# Adding new neighbours to queue
search_queue += graph[person]
# Add current searched person to searched list
searched.append(person)
print("No mango sellers in your friends list :(")
return False
bfs()