Skip to content

Instantly share code, notes, and snippets.

@zohaib304
Last active April 28, 2021 17:33
Show Gist options
  • Save zohaib304/2e3d8b9af60dbe4fe6acc5a0f651f028 to your computer and use it in GitHub Desktop.
Save zohaib304/2e3d8b9af60dbe4fe6acc5a0f651f028 to your computer and use it in GitHub Desktop.
Breadth Frist Search (BFS)
# adjancy list...which can be represent as python dictionary
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : ['A'],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] # Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# function cal
bfs(visited, graph, 'D')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment