
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
BFS for Disconnected Graph in C++
Disconnected graph is a Graph in which one or more nodes are not the endpoints of the graph i.e. they are not connected.
A disconnected graph…
Now, the Simple BFS is applicable only when the graph is connected i.e. all vertices of the graph are accessible from one node of the graph. in the above disconnected graph technique is not possible as a few laws are not accessible so the following changed program would be better for performing breadth first search in a disconnected graph.
Example
#include<bits/stdc++.h> using namespace std; void insertnode(vector<int> adj[], int u, int v) { adj[u].push_back(v); } void breathFirstSearch(int u, vector<int> adj[], vector<bool> &visited) { list<int> q; visited[u] = true; q.push_back(u); while(!q.empty()) { u = q.front(); cout << u << " "; q.pop_front(); for (int i = 0; i != adj[u].size(); ++i) { if (!visited[adj[u][i]]) { visited[adj[u][i]] = true; q.push_back(adj[u][i]); } } } } void BFSdisc(vector<int> adj[], int V) { vector<bool> visited(V, false); for (int u=0; u<V; u++) if (visited[u] == false) breathFirstSearch(u, adj, visited); } int main() { int V = 5; vector<int> adj[V]; insertnode(adj, 0, 23); insertnode(adj, 0, 4); insertnode(adj, 1, 2); insertnode(adj, 1, 3); insertnode(adj, 1, 4); insertnode(adj, 2, 3); insertnode(adj, 3, 4); BFSdisc(adj, V); return 0; }
Output
0 4 1 2 3
- Related Articles
- Breadth First Search (BFS) for a Graph
- Breadth First Search or BFS for a Graph
- C++ Program to Check the Connectivity of Undirected Graph Using BFS
- C++ Program to Check the Connectivity of Directed Graph Using BFS
- C++ Program to Check whether Graph is a Bipartite using BFS
- Python Program to Find if Undirected Graph contains Cycle using BFS
- Python Program to Find All Connected Components using BFS in an Undirected Graph
- BFS vs DFS for Binary Tree in C++?
- BFS using STL for competitive coding in C++?
- Print the lexicographically smallest BFS of the graph starting from 1 in C Program.
- Connected vs Disconnected Graphs
- C++ Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected\n
- Python Program to Find All Nodes Reachable from a Node using BFS in a Graph
- What are connected and disconnected Row Sets in JDBC?
- Check For Star Graph

Advertisements