Open In App

Program to print all the non-reachable nodes | Using BFS

Last Updated : 06 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an undirected graph and a set of vertices, we have to print all the non-reachable nodes from the given head node using a breadth-first search.

For example:  

Consider below undirected graph with two disconnected components: 
 

In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as visited. All those nodes which are not marked as visited i.e, node 3 and 4 are non-reachable nodes. 
 

Examples: 

Input: 5
       0 1
       0 2
       1 2
       3 4
Output: 3 4

Input: 8
       0 1
       0 2
       1 2
       3 4
       4 5
       6 7
Output: 3 4 5 6 7

Approach: 

  • We can either use BFS or DFS for this purpose. Set 1 of this article implements the DFS approach. In this article, BFS approach is used.
  • We do BFS from a given source. Since the given graph is undirected, all the vertices that belong to the disconnected component are non-reachable nodes. We use the visited array for this purpose, the array which is used to keep track of non-visited vertices in BFS. 
  • BFS is a traversing algorithm which starts traversing from a selected node (source or starting node) and traverses the graph layer-wise thus exploring the neighbour nodes (nodes which are directly connected to source node). Then, move towards the next-level neighbour nodes. 
     

Below is the implementation of the above approach:  

C++




// C++ program to count non-reachable nodes
// from a given source using BFS.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to add an edge to graph
void add_edge(vector<int> adj[],
              int v, int w)
{
    // Add w to v’s list.
    adj[v].push_back(w);
 
    // Add v to w's list.
    adj[w].push_back(v);
}
 
// BFS traversal of the vertices
// reachable from starting node
void BFS(vector<int> adj[], int s,
         int v)
{
    // Mark all the vertices
    // as not visited
    bool visited[v] = { false };
 
    // Create a queue for BFS
    queue<int> q;
 
    // Mark the current node as
    // visited and enqueue it
    q.push(s);
    visited[s] = true;
 
    while (!q.empty()) {
        // Dequeue a vertex from
        // queue
        int p = q.front();
        q.pop();
 
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        for (auto it = adj[p].begin();
             it != adj[p].end(); it++) {
            if (!visited[*it]) {
                visited[*it] = true;
                q.push(*it);
            }
        }
    }
    for (int i = 0; i < v; i++) {
        if (!visited[i]) {
            cout << i << " ";
        }
    }
    cout << "\n";
}
 
// Drivers code
int main()
{
    // Create a graph given in
    // the above diagram
    vector<int> adj[8];
    add_edge(adj, 0, 1);
    add_edge(adj, 0, 2);
    add_edge(adj, 1, 2);
    add_edge(adj, 3, 4);
    add_edge(adj, 4, 5);
    add_edge(adj, 6, 7);
 
    BFS(adj, 0, 8);
 
    return 0;
}


Java




// Java program to count non-reachable nodes
// from a given source using BFS.
import java.util.*;
 
class GFG{
  
// Function to add an edge to graph
static void add_edge(Vector<Integer> adj[],
              int v, int w)
{
    // Add w to v’s list.
    adj[v].add(w);
  
    // Add v to w's list.
    adj[w].add(v);
}
  
// BFS traversal of the vertices
// reachable from starting node
static void BFS(Vector<Integer> adj[], int s,
         int v)
{
    // Mark all the vertices
    // as not visited
    boolean []visited = new boolean[v];
  
    // Create a queue for BFS
    Queue<Integer> q = new LinkedList<>();
  
    // Mark the current node as
    // visited and enqueue it
    q.add(s);
    visited[s] = true;
  
    while (!q.isEmpty()) {
 
        // Dequeue a vertex from
        // queue
        int p = q.peek();
        q.remove();
  
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        for (int it : adj[p]) {
            if (!visited[it]) {
                visited[it] = true;
                q.add(it);
            }
        }
    }
    for (int i = 0; i < v; i++) {
        if (!visited[i]) {
            System.out.print(i+ " ");
        }
    }
    System.out.print("\n");
}
  
// Drivers code
public static void main(String[] args)
{
    // Create a graph given in
    // the above diagram
    Vector<Integer> []adj = new Vector[8];
    for (int i = 0; i < 8; i++)
        adj[i] = new Vector<Integer>();
    add_edge(adj, 0, 1);
    add_edge(adj, 0, 2);
    add_edge(adj, 1, 2);
    add_edge(adj, 3, 4);
    add_edge(adj, 4, 5);
    add_edge(adj, 6, 7);
  
    BFS(adj, 0, 8);
  
}
}
 
// This code is contributed by sapnasingh4991


Python3




# Python3 program to count non-reachable
# nodes from a given source using BFS
 
# Function to add an edge to graph
def add_edge(adj, v, w):
     
    # Add w to v’s list
    adj[v].append(w)
 
    # Add v to w's list
    adj[w].append(v)
 
# BFS traversal of the vertices
# reachable from starting node
def BFS(adj, s, v):
 
    # Mark all the vertices
    # as not visited
    visited = [False for i in range(v)]
 
    # Create a queue for BFS
    q = []
 
    # Mark the current node as
    # visited and enqueue it
    q.append(s)
    visited[s] = True
 
    while (len(q) != 0):
       
        # Dequeue a vertex from
        # queue
        p = q[0]
        q.pop(0)
 
        # Get all adjacent vertices
        # of the dequeued vertex p.
        # If a adjacent has not been
        # visited, then mark it
        # visited and enqueue it
        for it in adj[p]:
            if (not visited[it]):
                visited[it] = True
                q.append(it)
             
    for i in range(v):
        if (not visited[i]):
            print(i, end = ' ')
             
    print()
     
# Driver code
if __name__=='__main__':
 
    # Create a graph given in
    # the above diagram
    adj = [[] for i in range(8)]
     
    add_edge(adj, 0, 1)
    add_edge(adj, 0, 2)
    add_edge(adj, 1, 2)
    add_edge(adj, 3, 4)
    add_edge(adj, 4, 5)
    add_edge(adj, 6, 7)
     
    BFS(adj, 0, 8)
 
# This code is contributed by rutvik_56


C#




// C# program to count non-reachable nodes
// from a given source using BFS.
using System;
using System.Collections.Generic;
 
class GFG{
   
// Function to add an edge to graph
static void add_edge(List<int> []adj,
              int v, int w)
{
    // Add w to v’s list.
    adj[v].Add(w);
   
    // Add v to w's list.
    adj[w].Add(v);
}
   
// BFS traversal of the vertices
// reachable from starting node
static void BFS(List<int> []adj, int s,
         int v)
{
    // Mark all the vertices
    // as not visited
    bool []visited = new bool[v];
   
    // Create a queue for BFS
    List<int> q = new List<int>();
   
    // Mark the current node as
    // visited and enqueue it
    q.Add(s);
    visited[s] = true;
   
    while (q.Count != 0) {
  
        // Dequeue a vertex from
        // queue
        int p = q[0];
        q.RemoveAt(0);
   
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        foreach (int it in adj[p]) {
            if (!visited[it]) {
                visited[it] = true;
                q.Add(it);
            }
        }
    }
    for (int i = 0; i < v; i++) {
        if (!visited[i]) {
            Console.Write(i + " ");
        }
    }
    Console.Write("\n");
}
   
// Driver's code
public static void Main(String[] args)
{
    // Create a graph given in
    // the above diagram
    List<int> []adj = new List<int>[8];
    for (int i = 0; i < 8; i++)
        adj[i] = new List<int>();
    add_edge(adj, 0, 1);
    add_edge(adj, 0, 2);
    add_edge(adj, 1, 2);
    add_edge(adj, 3, 4);
    add_edge(adj, 4, 5);
    add_edge(adj, 6, 7);
   
    BFS(adj, 0, 8);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript program to count non-reachable
// nodes from a given source using BFS
 
// Function to add an edge to graph
function add_edge(adj, v, w){
     
    // Add w to v’s list
    adj[v].push(w)
 
    // Add v to w's list
    adj[w].push(v)
}
 
// BFS traversal of the vertices
// reachable from starting node
function BFS(adj, s, v){
 
    // Mark all the vertices
    // as not visited
    let visited = new Array(v).fill(false)
 
    // Create a queue for BFS
    let q = []
 
    // Mark the current node as
    // visited and enqueue it
    q.push(s)
    visited[s] = true
 
    while (q.length != 0){
     
        // Dequeue a vertex from
        // queue
        let p = q.shift()
 
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        for(let it of adj[p]){
            if (!visited[it]){
                visited[it] = true
                q.push(it)
            }
        }
    }
             
    for(let i=0;i<v;i++){
        if (!visited[i]){
            document.write(i,' ')
        }
    }
             
    document.write("</br>")
}
     
// Driver code
 
// Create a graph given in
// the above diagram
let adj = new Array(8)
for(let i=0;i<8;i++){
    adj[i] = new Array()
}
 
add_edge(adj, 0, 1)
add_edge(adj, 0, 2)
add_edge(adj, 1, 2)
add_edge(adj, 3, 4)
add_edge(adj, 4, 5)
add_edge(adj, 6, 7)
 
BFS(adj, 0, 8)
 
// This code is contributed by Shinjanpatra
 
</script>


Output: 

3 4 5 6 7

 



Previous Article
Next Article

Similar Reads

Count the number of non-reachable nodes
Given an undirected graph and a set of vertices, we have to count the number of non-reachable nodes from the given head node using a depth-first search. Consider below undirected graph with two disconnected components: In this graph, if we consider 0 as a head node, then the node 0, 1 and 2 are reachable. We mark all the reachable nodes as visited.
13 min read
Find all reachable nodes from every node present in a given set
Given an undirected graph and a set of vertices, find all reachable nodes from every vertex present in the given set. Consider below undirected graph with 2 disconnected components. arr[] = {1 , 2 , 5} Reachable nodes from 1 are 1, 2, 3, 4 Reachable nodes from 2 are 1, 2, 3, 4 Reachable nodes from 5 are 5, 6, 7Method 1 (Simple) One straight forward
12 min read
Count nodes with maximum reachable neighbours at a d distance
Given a graph with n nodes and m edges, each edges[i] = [u, v, weight] and d as the maximum distance to reach the neighbor nodes, the task is to find the total number of nodes with maximum reachable neighbors. Input: n = 4, edges = [[0, 1, 3], [1, 2, 1], [1, 3, 4], [2, 3, 1]], d = 4 [caption width="800"]Example 1[/caption] Output: 2Explanation: nod
10 min read
Maximum Nodes removed to Keep the Graph Reachable
You and your Friend are given an undirected graph having 3 types of edges. A graph is called Reachable if starting from any node, you and your friend can reach all other nodes. Print the maximum number of edges that you can remove in order for the graph to remain Reachable. or print -1. Type 1: could be traveled by you only Type 2: could be travele
10 min read
CSES Solutions – Reachable Nodes
A directed acyclic graph consists of n nodes and m edges. The nodes are numbered 1,2,…,n. Calculate for each node the number of nodes you can reach from that node (including the node itself). Examples: Input: n = 5, m = 6, edges = {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {3, 5}, {4, 5}}Output: 5 3 2 2 1Explanation: From node 1, we can reach nodes 1, 2, 3,
8 min read
Print all paths from a given source to a destination using BFS
Given a directed graph, a source vertex ‘src’ and a destination vertex ‘dst’, print all paths from given ‘src’ to ‘dst’. Consider the following directed graph. Let the src be 2 and dst be 3. There are 3 different paths from 2 to 3. Recommended: Please solve it on “PRACTICE” first, before moving on to the solution. We have already discussed Print al
9 min read
Count the number of nodes at given level in a tree using BFS.
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traversing from a selected node (source or starting node
9 min read
Find count of pair of nodes at even distance | Set 2 (Using BFS)
Given a connected acyclic graph with N nodes numbered from 1 to N and N-1 edges, find out the pair of nodes that are at even distance from each other. Note: The graph is represented in the form of an adjacency list. Examples: Input: N = 3, graph = {{}, {2}, {1, 3}, {2}}Output:1Explanation: Here there are three pairs {1, 2}, {1, 3}and {2, 3} and onl
8 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Furthest Reachable Tower using Blocks and Ladders
Given an array heights[] of size N, where heights[i] is the height of the ith tower. We are standing at the 0th tower with B blocks and L ladders and we have to reach the furthest tower possible by jumping on adjacent towers. For ith tower, If heights[i + 1] &lt;= heights[i], then we can simply jump to the next tower. Else,If heights[i + 1] &gt; he
13 min read
Article Tags :
Practice Tags :