Subscribe Us

Responsive Advertisement

Advertisement

Problem 16: a graph is connected or not using DFS|C++

 

Problem 16: a graph is connected or not using DFS|C++

by Ujjal Roy



#include<bits/stdc++.h>

using namespace std;

#define ll long long int

const ll N=1000;

vector<ll>adj[N];

ll vis[N];

void dfs(ll node)

{

    vis[node]=1;

    for(auto u:adj[node])

    {

        if(vis[u]==0)

        {

            dfs(u);

        }

    }

}

int main()

{

    cout<<"Enter Number of node and edge : ";

    ll node,edge,i;

    cin>>node>>edge;

    while(edge--)

    {

        ll u,v;

        cin>>u>>v;

        adj[u].push_back(v);

        adj[v].push_back(u);

    }

    dfs(0);

    ll check;

    check=0;

    for(i=1;i<node;i++)

    {

        if(vis[i]==0)

        {

            check=1;

            break;

        }

    }

    if(check)cout<<"Not connected\n";

    else cout<<"Connected\n";


    return 0;

}


Post a Comment

0 Comments