Here Is my python code:
JavaScript
x
30
30
1
# Using a Python dictionary to act as an adjacency list
2
graph = {
3
'A' : ['B','C','D'],
4
'B' : ['E', 'F'],
5
'C' : ['G'],
6
'E' : [],
7
'F' : [],
8
'G' : ['K','H'],
9
'K' : [],
10
'H' : [],
11
'D' : [],
12
13
14
}
15
16
visited = set() # Set to keep track of visited nodes of graph.
17
18
def dfs(visited, graph, node): #function for dfs
19
if node not in visited:
20
print (node)
21
visited.add(node)
22
for neighbour in graph[node]:
23
dfs(visited, graph, neighbour)
24
break
25
26
27
# Driver Code
28
print("Following is the Depth-First Search")
29
dfs(visited, graph, 'A')
30
its about depth first search algorithm and when I compile it without break statement the result would be: A B E F C G K H D
and when i put break statement the result would be: A B E and my question is how i can here stop this algorithm at specific node like F so the result would be like
A B E F
I have tried to put break after line 23 but it just give me this result A B E but I want F to be included in it
Advertisement
Answer
In order to stop the loop, we would want to return something if the node, for which you are searching for, is found:
JavaScript
1
39
39
1
# Using a Python dictionary to act as an adjacency list
2
graph = {
3
'A': ['B', 'C', 'D'],
4
'B': ['E', 'F'],
5
'C': ['G'],
6
'E': [],
7
'F': [],
8
'G': ['K', 'H'],
9
'K': [],
10
'H': [],
11
'D': [],
12
13
}
14
15
visited = set() # Set to keep track of visited nodes of graph.
16
17
18
def dfs(visited, graph, node, stop_at): # function for dfs
19
if node not in visited:
20
print(node)
21
22
# We check if the current node is the one for which we are looking for
23
if node == stop_at:
24
return True
25
26
visited.add(node)
27
for neighbour in graph[node]:
28
# If we found the node, we break out from the loop
29
if dfs(visited, graph, neighbour, stop_at):
30
return True
31
# If we did not find the node we were looking for, we return False
32
return False
33
34
35
# Driver Code
36
if __name__ == "__main__":
37
print("Following is the Depth-First Search")
38
dfs(visited, graph, 'A', 'F')
39
In case of dfs(visited, graph, 'A', 'F')
, it should print:
JavaScript
1
5
1
A
2
B
3
E
4
F
5