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

PythonServer Side ProgrammingProgramming

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 add_edge(v, w):

   global visited_node, adj
   adj[v].append(w)
   adj[w].append(v)

def BFS_operation(component_num, src):

   global visited_node, adj
   queue = deque()

   queue.append(src)

   visited_node[src] = 1
   reachableNodes = []

   while (len(queue) > 0):

      u = queue.popleft()
      reachableNodes.append(u)
      for itr in adj[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):

   global V, adj, visited_node

   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)]
add_edge(1, 2)
add_edge(2, 3)
add_edge(3, 4)
add_edge(3, 1)
add_edge(5, 6)
add_edge(5, 7)

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.

  • The ‘add_edge’ methods adds nodes to the graph.

  • A list is defined and displayed on the console.

  • The method is called and the output is displayed on the console.

raja
Published on 17-Apr-2021 11:45:06
Advertisements