PYTHON ALGORITHM…AGAIN.(Depth first search(Dfs))

Che Kai LIANG
2 min readJan 9, 2022

I think you all now why we are here. ANOTHER PYTHON ALGORITHM POST. SERIOUSLY. Why are you guys so interested in this god damn topic? Huh? ANSWER ME NERDS! WHY ARE YOU MAKING WRITE ANOTHER ONE OF THESE —

*Sorry, we are encountering technical issues, please stand by~*

*Sigh.* Hello. Welcome to another python algorithm post. Today we will be talking about Depth first search(DFS for short.) Not very different from the breadth first search. Look up that post if you want. Here: https://chekailiang.medium.com/bfs-breadth-first-search-692e35605d23 Here is part 2: https://chekailiang.medium.com/bfs-breadth-first-search-pt-2-cc079d1bd2d1

I do not recommend them. Do not check them out. No one is going to look at these posts anyway. Eh. Does not matter. For the 0 amount of people reading this: Medium sucks.

Anyway, DFS uses more of a stack system, unlike the queue method deloyed by BFS. Here is an example:

def dfs(graph, node,   path=[]):path += [node]for n in graph[node]:if n not in path:path = dfs(graph, n, path)return pathgraph = {'A':['B', 'C', 'D'],'B':['A', 'E'],'C':['A', 'F'],'D':['A', 'G', 'H'],'E':['B'],'F':['C', 'I', 'J'],'G':['D'],'H':['D'],'I':['F'],'J':['F']}print(dfs (graph,'A'))

Here is the result if your copy & paste is not malfunctioning.

:P

You are welcome.

Bye.

--

--