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

«
»

This is a Python program to find all nodes reachable from a node using BFS in a graph.

Problem Description

The program creates a graph object and allows the user to find all nodes reachable from a node.

Problem Solution

1. Create classes for Graph, Vertex and Queue.
2. Create a function find_all_reachable_nodes that takes a Vertex object as argument.
3. The function begins by creating an empty set called visited and a Queue object, q.
4. It enqueues the passed Vertex object and also adds it to the set visited.
5. A while loop is created which runs as long as the queue is no empty.
6. In each iteration of the loop, the queue is dequeued and all of its neighbours are enqueued which have not already been visited.
7. In addition to enqueuing, they are also added to the visited set.
8. After the loop is finished, the set visited is returned. The set contains all vertices that can be reached from the source vertex.
9. This algorithm also works for undirected graphs. In an undirected graph, whenever edge (u, v) is added to the graph, the reverse edge (v, u) is also added.

advertisement
Program/Source Code

Here is the source code of a Python program to find all nodes reachable from a node using BFS in a graph. The program output is shown below.

class Graph:
    def __init__(self):
        # dictionary containing keys that map to the corresponding vertex object
        self.vertices = {}
 
    def add_vertex(self, key):
        """Add a vertex with the given key to the graph."""
        vertex = Vertex(key)
        self.vertices[key] = vertex
 
    def get_vertex(self, key):
        """Return vertex object with the corresponding key."""
        return self.vertices[key]
 
    def __contains__(self, key):
        return key in self.vertices
 
    def add_edge(self, src_key, dest_key, weight=1):
        """Add edge from src_key to dest_key with given weight."""
        self.vertices[src_key].add_neighbour(self.vertices[dest_key], weight)
 
    def does_edge_exist(self, src_key, dest_key):
        """Return True if there is an edge from src_key to dest_key."""
        return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])
 
    def __iter__(self):
        return iter(self.vertices.values())
 
 
class Vertex:
    def __init__(self, key):
        self.key = key
        self.points_to = {}
 
    def get_key(self):
        """Return key corresponding to this vertex object."""
        return self.key
 
    def add_neighbour(self, dest, weight):
        """Make this vertex point to dest with given edge weight."""
        self.points_to[dest] = weight
 
    def get_neighbours(self):
        """Return all vertices pointed to by this vertex."""
        return self.points_to.keys()
 
    def get_weight(self, dest):
        """Get weight of edge from this vertex to dest."""
        return self.points_to[dest]
 
    def does_it_point_to(self, dest):
        """Return True if this vertex points to dest."""
        return dest in self.points_to
 
 
class Queue:
    def __init__(self):
        self.items = []
 
    def is_empty(self):
        return self.items == []
 
    def enqueue(self, data):
        self.items.append(data)
 
    def dequeue(self):
        return self.items.pop(0)
 
 
def find_all_reachable_nodes(vertex):
    """Return set containing all vertices reachable from vertex."""
    visited = set()
    q = Queue()
    q.enqueue(vertex)
    visited.add(vertex)
    while not q.is_empty():
        current = q.dequeue()
        for dest in current.get_neighbours():
            if dest not in visited:
                visited.add(dest)
                q.enqueue(dest)
    return visited
 
 
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('reachable <vertex key>')
print('display')
print('quit')
 
while True:
    do = input('What would you like to do? ').split()
 
    operation = do[0]
    if operation == 'add':
        suboperation = do[1]
        if suboperation == 'vertex':
            key = int(do[2])
            if key not in g:
                g.add_vertex(key)
            else:
                print('Vertex already exists.')
        elif suboperation == 'edge':
            src = int(do[2])
            dest = int(do[3])
            if src not in g:
                print('Vertex {} does not exist.'.format(src))
            elif dest not in g:
                print('Vertex {} does not exist.'.format(dest))
            else:
                if not g.does_edge_exist(src, dest):
                    g.add_edge(src, dest)
                else:
                    print('Edge already exists.')
 
    elif operation == 'reachable':
        key = int(do[1])
        vertex = g.get_vertex(key)
        reachable = find_all_reachable_nodes(vertex)
        print('All nodes reachable from {}:'.format(key),
              [v.get_key() for v in reachable])
 
    elif operation == 'display':
        print('Vertices: ', end='')
        for v in g:
            print(v.get_key(), end=' ')
        print()
 
        print('Edges: ')
        for v in g:
            for dest in v.get_neighbours():
                w = v.get_weight(dest)
                print('(src={}, dest={}, weight={}) '.format(v.get_key(),
                                                             dest.get_key(), w))
        print()
 
    elif operation == 'quit':
        break
Program Explanation

1. An instance of Graph is created.
2. A menu is presented to the user to perform various operations on the graph.
3. To find all nodes reachable from a vertex, find_all_reachable_nodes is called.

advertisement
advertisement
Runtime Test Cases
Case 1:
Menu
add vertex <key>
add edge <src> <dest>
reachable <vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? reachable 1
All nodes reachable from 1: [1]
What would you like to do? add edge 1 2
What would you like to do? reachable 1
All nodes reachable from 1: [2, 1]
What would you like to do? reachable 2
All nodes reachable from 2: [2]
What would you like to do? add edge 2 1
What would you like to do? reachable 2
All nodes reachable from 2: [2, 1]
What would you like to do? add vertex 3
What would you like to do? add edge 2 3
What would you like to do? add vertex 4
What would you like to do? add edge 3 4
What would you like to do? reachable 1
All nodes reachable from 1: [2, 3, 1, 4]
What would you like to do? quit
 
Case 2:
Menu
add vertex <key>
add edge <src> <dest>
reachable <vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
What would you like to do? add edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 5 4
What would you like to do? reachable 4
All nodes reachable from 4: [4]
What would you like to do? reachable 5
All nodes reachable from 5: [4, 5]
What would you like to do? reachable 1
All nodes reachable from 1: [2, 3, 1]
What would you like to do? reachable 2
All nodes reachable from 2: [2, 3]
What would you like to do? reachable 3
All nodes reachable from 3: [3]
What would you like to do? quit

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter