devmingle
Home
Categories
Popular Codes
Articles
/
Python
/
DFS
DFS
Dfs
# Depth First Search: DFS Algorithm # 1) Pick any node. # 2) If it is unvisited, mark it as visited and recur on all its # adjacent (neighbours) nodes. # 3) Repeat until all the nodes are visited graph= { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } visited = set() # Set to keep track of visited nodes of graph. def dfs(visited, graph, node): #function for dfs if node not in visited: ''' We start with A Then B Then D Then E Then F Then C A -> B -> D -> E -> F -> C ''' print(node) # added to visited to avoid visit the node twice visited.add(node) for neighbour in graph[node]: ''' * Neighbour of A : B and C but first visit B * Then neighbour of B : D and E but first visit D * Then neighbour of D : doesn't have neighbour then backtrack to the neighbour of the previous node (B) which is E * Then neighbour of E : F * Then neighbour of F : doesn't have neighbour then backtrack to the neighbour of the previous node E but doesn't have other neighbour except F which is visited So backtracking again to B and B also doesn't have nodes not visited So backtracking again to A: C not visited YAY! ''' dfs(visited, graph, neighbour) print(dfs(visited, graph, 'A'))
1
DFS explained
def depth_first_search(graph): visited, stack = set(), [root] while stack: vertex = stack.pop() if vertex not in visited: visited.add(vertex) stack.extend(graph[vertex] - visited) return visited
0
Source:
brilliant.org
DFS explained
Initialize an empty stack for storage of nodes, S. For each vertex u, define u.visited to be false. Push the root (first node to be visited) onto S. While S is not empty: Pop the first element in S, u. If u.visited = false, then: U.visited = true for each unvisited neighbor w of u: Push w into S. End process when all nodes have been visited.
0
Source:
brilliant.org
DFS
print("found ans")
-3
Source:
purdue.brightspace.com
Share
Similar codes
0 vote
85 views
1 answer
How to import files from desktop to python
Python
0 vote
94 views
1 answer
Reset button combobocx tkinter
Python
0 vote
100 views
1 answer
Custom pylatex command
Python
1 vote
89 views
1 answer
Slack send message python
Python
0 vote
111 views
1 answer
Adding bootstrap grid dynamically django
Python
Django
0 vote
87 views
1 answer
How to handle missing values in dataset
Python
2 votes
92 views
1 answer
Distribution seaborn
Python
8 votes
42 views
2 answers
Python selenium get image src
Python
0 vote
105 views
1 answer
Back button django template
Python
Django
3 votes
94 views
2 answers
Python print do not use scientific notation
Python
Share