BFS — Breadth First Search PT.2

def is_exit(node): #Defineif node == 'K': #nodereturn True def bfs(graph, start):global visitedqueue = [start]#queuewhile queue:node = queue.pop(0)if is_exit(node):print(node + 'Exit')#The searched variablevisited.append(node)#Visited listreturn visitedif node not in visited: visited.append(node)neighbors = graph[node]for n in neighbors: #define neighbors(linked alphabets)queue.append(n)return visited graph = {'A':['B'],'B':['A', 'C'],'C':['B', 'D', 'E'],'D':['C'],'E':['C', 'H'],'F':['G'],'G':['F', 'H', 'J'],'H':['E', 'G', 'I'],'I':['H', 'K'],'J':['G'],'K':['I']}visited = []print(bfs(graph, 'A'))
The result

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store