BFS Algorithm
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
[Link](node)
[Link](node)
while queue: # Creating loop to visit each node
m = [Link](0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
DFS Algorithm
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node)
[Link](node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Greedy algorithm (coin change)
def greedy_coin_change(amount, denominations):
[Link](reverse=True) # Sort denominations in descending
order
coins_used = []
for coin in denominations:
while amount >= coin:
coins_used.append(coin)
amount -= coin
return coins_used
# Example usage:
amount_to_change = 63
coin_denominations = [1, 2, 5, 10, 20, 50]
result = greedy_coin_change(amount_to_change, coin_denominations)
print("Coins Used:", result)
print("Total Coins:", len(result))
A* Algorithm
def astaralgo(start_node,stop_node):
open_set = set(start_node)
closed_set= set()
g={}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
while len(open_set) > 0:
n=None
for v in open_set:
if n==None or g[v] + heuristic(v) < g[n] + heuristic(n):
n=v
if n==stop_node or Graph_nodes[n]==None:
pass
else:
for(m,weight) in get_neighbors(n):
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m]=n
g[m] = g[n] + weight
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m]=n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n==None:
print("path does not exist!")
return None
if n==stop_node:
path=[]
while parents[n]!=n:
[Link](n)
n=parents[n]
[Link](start_node)
[Link]()
print("Path found: {}".format(path))
return path
open_set.remove(n)
closed_set.add(n)
print("Path does not exist!")
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A' : 11,
'B' : 6,
'C' : 99,
'D' : 1,
'E' : 7,
'G' : 0,
return H_dist[n]
Graph_nodes = {
'A' : [('B',2),('E',3)],
'B' : [('C',1),('G',9)],
'C' : None,
'E' : [('D',6)],
'D' : [('G',1)],
astaralgo('A','G')