Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jiachen247/739a6368ca86105dc3ff85d5a2141fc1 to your computer and use it in GitHub Desktop.
Save jiachen247/739a6368ca86105dc3ff85d5a2141fc1 to your computer and use it in GitHub Desktop.
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