Check if a directed graph is connected or not in C++

To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.

For the directed graph, we will start traversing from all nodes to check connectivity. Sometimes one edge can have only outward edge but no inward edge, so that node will be unvisited from any other starting node.

In this case the traversal algorithm is recursive DFS traversal.

Input − Adjacency matrix of a graph


Output − The Graph is connected.


traverse(u, visited)
Input: The start node u and the visited node to mark which node is visited.
Output: Traverse all connected vertices.
   mark u as visited
   for all vertex v, if it is adjacent with u, do
      if v is not visited, then
         traverse(v, visited)
Input: The graph.
Output: True if the graph is connected.
   define visited array
   for all vertices u in the graph, do
      make all nodes unvisited
      traverse(u, visited)
      if any unvisited node is still remaining, then
         return false
   return true


 Live Demo

#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 0, 0, 0},
   {0, 0, 1, 0, 0},
   {0, 0, 0, 1, 1},
   {1, 0, 0, 0, 0},
   {0, 1, 0, 0, 0}
void traverse(int u, bool visited[]){
   visited[u] = true; //mark v as visited
   for(int v = 0; v<NODE; v++){
         traverse(v, visited);
bool isConnected(){
   bool *vis = new bool[NODE];
   //for all vertex u as start point, check whether all nodes are visible or not
   for(int u; u < NODE; u++){
      for(int i = 0; i<NODE; i++)
      vis[i] = false; //initialize as no node is visited
      traverse(u, vis);
      for(int i = 0; i<NODE; i++){
         if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
         return false;
   return true;
int main(){
   cout << "The Graph is connected.";
   cout << "The Graph is not connected.";


The Graph is connected.

Updated on: 25-Sep-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started