Program to print all the non-reachable nodes | Using BFS
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 |
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 |
3 4 5 6 7
Got what you were looking for? Learn more and become self sufficient. Start learning Data Sructures & Algorithms with the help of the most trusted DSA Self Paced course, and that too at the most student-friendly price.
Recommended Posts:
- Hexadecimal equivalents in Binary Valued Graph
- Find any one of the multiple repeating elements in read only array | Set 2
- Proof that Hamiltonian Cycle is NP-Complete
- Check if the end of the Array can be reached from a given position
- Find if there is a path between two vertices in an undirected graph
- Binary Search Tree | Set 3 (Iterative Delete)
- Shortest path in a directed graph by Dijkstra’s algorithm
- Check if given intervals can be made non-overlapping by adding/subtracting some X
- Maximum difference of count of black and white vertices in a path containing vertex V
- Real-time application of Data Structures
- Check if the given permutation is a valid BFS of a given Tree
- Proof that Dominant Set of a Graph is NP-Complete
- Proof that traveling salesman problem is NP Hard
- Shortest Path with even number of Edges from Source to Destination
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


