BFS (Breadth First Search)
a simple implementation in python
Table of contents
Solution
def bfs(graph, visited):
queue = []
queue.append("a")
visited["a"] = True
while queue:
temp = queue.pop(0)
print(temp)
for item in graph[temp]:
if not visited.get(item):
queue.append(item)
visited[item] = True
node = ["a", "b", "c", "d", "e", "g", "f"]
edges = [["a", "b"], ["b", "c"], ["b", "e"], ["c", "d"], ["c", "e"],
["e", "g"], ["f", "f"]]
graph = {}
visited = {}
for i in node:
graph[i] = []
for (u, v) in edges:
graph[u].append(v)
graph[v].append(u)
bfs(graph, visited)