Created
May 31, 2022 02:30
-
-
Save jiachen247/739a6368ca86105dc3ff85d5a2141fc1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
graph = { | |
'a' : ['b','c'], | |
'b' : ['d'], | |
'c' : ['e'], | |
'd' : ['f'], | |
'e' : [], | |
'f' : [] | |
} | |
visited = set() # List to keep track of visited nodes. | |
queue = [] #Initialize a queue | |
def bfs(node, target): | |
visited.add(node) | |
queue.append(node) | |
while queue: | |
s = queue.pop(0) | |
print(s) | |
if s == target: | |
return True | |
for neighbour in graph[s]: | |
if neighbour not in visited: | |
visited.add(node) | |
queue.append(neighbour) | |
return False | |
# Driver Code | |
print(bfs('a', 'd')) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment