BFS — Breadth First Search PT.2

Che Kai LIANG
2 min readJan 1, 2022

Why hello there.

Why are you still here?

Oh, right, you came here for more BFS?

Ok?

What about no?

Fine.

I hate you.

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'))

Here.

WHAT?

I HAVE TO EXPLAIN THIS?!

Fine.

FINE!

Whats happening here is that every single variable is being controlled if it is the one we are looking for. One after another. The order is like a tree. Every variable is linked, so when we are check one of them, we go to the linked variables. If a variable is the one we are looking for, the program ends. If it is not however, we put it aside.

WHAT IS IT?!

I HAVE TO EXPLAIN MORE?

WHO DO YOU THINK I AM? A MEDIUM WRITER?

Wait…

The if loop will keep checking the variables in the above mentioned order. If the node is not the one we are looking for, we put it in the visited list. So if a node is not visited, we check it. If it is the one we are looking for, program end. If it is not, put in visited list. The neighbors of the visited variables are then put into queue. We define this action, in the code, using bfs. After we run it, we set up a tangled list of the alphabets, then using the defined bfs, we sort through them using breadth first search. Here is the result:

The result

NOW ARE WE DONE?

More?

--

--