Python Program to Find All Nodes Reachable from a Node using BFS in a Graph

When it is required to find the sum of all the nodes of a tree, a class is created, and it contains methods to set the root node, add elements to the tree, search for a specific element, and add elements of the tree to find the sum and so on. An instance of the class can be created to access and use these methods.

Below is a demonstration of the same −

Example

Live Demo

from collections import deque

def BFS_operation(component_num, src):

queue = deque()

queue.append(src)

visited_node[src] = 1
reachableNodes = []

while (len(queue) > 0):

u = queue.popleft()
reachableNodes.append(u)
if (visited_node[itr] == 0):

visited_node[itr] = 1
queue.append(itr)

return reachableNodes

def displayReachableNodes(m):

for i in m:
print(i, end = " ")
print()

def findReachableNodes(my_list, n):

a = []

component_num = 0

for i in range(n):
u = my_list[i]

if (visited_node[u] == 0):
component_num += 1

a = BFS_operation(component_num, u)

print("The reachable nodes from ", u, " are")
displayReachableNodes(a)

V = 7
adj = [[] for i in range(V + 1)]
visited_node = [0 for i in range(V + 1)]

my_list = [ 2, 4, 5, 7 ]

arr_len = len(my_list)
findReachableNodes(my_list, arr_len)

Output

The reachable nodes from 2 are
2 1 3 4
The reachable nodes from 4 are
2 1 3 4
The reachable nodes from 5 are
5 6 7
The reachable nodes from 7 are
5 6 7

Explanation

• The required packages are imported.

• A method named ‘add_edge’ is defined that helps add elements to the tree.

• The ‘BFS_operation’ method helps traverse the tree using breadth first search approach.

• A method named ‘displayReachableNodes’ is defined, that helps display the nodes that can be reached from a specific node.

• A method named ‘findReachableNodes’ is defined, that iterates through the nodes, and performs ‘BFS_operation’ on the elements.