-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2538 from fawad1386/master
Depth First Search(Weighted Graph)
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
Program's_Contributed_By_Contributors/Python_Programs/Depth First Search(Weighted Graph).py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# Using a Python dictionary to act as an adjacency list | ||
graph = { | ||
'A' : [[8,'B'],[5,'E']], | ||
'B' : [[2,'D'],[1,'C']], | ||
'E' : [[1,'G']], | ||
'G' : [], | ||
'C' : [[3,'F']], | ||
'F' : [[4,'G']], | ||
'D' : [[3,'E']] | ||
|
||
} | ||
print("The Path Is = ",end = " ") | ||
found=0 | ||
visited = set() | ||
def dfs(visited, graph, node,goal): | ||
global found | ||
if found==1: | ||
return | ||
elif node not in visited: | ||
print(node,end=" ") | ||
if node ==goal: | ||
print ("\n***Goal Found***") | ||
found=1 | ||
return | ||
visited.add(node) | ||
templist=graph[node] | ||
templist.sort() | ||
for neighbour in templist: | ||
if len(neighbour)>0: | ||
dfs(visited, graph,neighbour[1],'G') | ||
dfs(visited, graph, 'A','G') |