Write java program BFS & DFS Algorithm.

graph = {'5':['3','7'],
 '3':['2','4','5'],
 '7':['8','5'],
 '2':['3','4'],
 '4':['2','3','8'],
 '8':['4','7']
 }
visited_bfs = []
visited_dfs = set()
queue = []
def bfs(visited_bfs, graph, node):
 visited_bfs.append(node)
 queue.append(node)
 while queue:
 m = queue.pop(0)
 print (m, end = " ")
 for neighbour in graph[m]:
 if neighbour not in visited_bfs:
 visited_bfs.append(neighbour)
 queue.append(neighbour)
def dfs(visited_dfs,graph,node):
 if node not in visited_dfs:
 print(node,end=" ")
 visited_dfs.add(node)
 for neighbour in graph[node]:
 dfs(visited_dfs,graph,neighbour)
print("Following is the Breadth-First Search")
bfs(visited_bfs, graph, '5')
print("\nFollowing is the Depth-First Search")
dfs(visited_dfs, graph, '5')

Output :



Post a Comment

1 Comments

  1. Cloud Financial Planning and Analysis (FP&A) solutions are innovative software platforms that leverage cloud computing technology to provide organizations with advanced financial planning and analysis capabilities. These solutions offer a range of features and tools that enable businesses to effectively manage their financial operations, make informed decisions, and drive overall performance and growth.

    ReplyDelete

Thanks,To visit this blog.