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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

AMA review:Announcement on the Organization Change of Defibox Foundation

Integrating physical devices with IOTA — Peer-to-peer energy trading with IOTA Part 2

How to build a secure chat app like whatsapp, wechat & viber?

Digital Owl’s Prose Newsletter — CodeIgniter, WordPress, Etsy

Substack Repost — OpenLampTech issue #22

Grease Trap Cleaning Thompson ND

Open source culture

Let’s compile your Aws Lambda in Java

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
Che Kai LIANG

Che Kai LIANG

More from Medium

Solving N-Queens for 1 Million Queens with MinConflict

My Journey as a Self-Taught Programmer

How to check if the concatenation of two substrings is a palindrome

Learn By Doing: Python Hangman Game