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 :
3 Comments
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.
ReplyDeleteThank you for this article on BFS and DFS algorithms in Java! It was really helpful in understanding both approaches. I especially appreciate the clear explanation of graph traversal and the code examples for both algorithms. The use of queues for BFS and stacks (or recursion) for DFS was well demonstrated. I successfully implemented them in my own project and tested them on various graph structures. This guide was exactly what I needed to grasp the core concepts and apply them in a practical setting!
ReplyDeleteI really enjoyed your posts! I wanted to share my blog, https://see-coding.blogspot.com/, where I offer coding tutorials and tips for developers. You might find some of the content helpful for your readers.
ReplyDeleteThanks for your great work!
Thanks,To visit this blog.