Solved programming problem

Find A Graph is Connected or Not in C++.

Source code

#include <iostream>

using namespace std;

int graph[100][100];

char vertex[26];

void create(int node)

{

    int i,j;

  ///Create all vertex

    for(i=0; i<26; i++)

    {

        vertex[i]=65+i;

    }

    ///set all value 0 for each node

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

    {

        for(j=0; j<node; j++)

        {

            graph[i][j]=0;

        }

    }

     ///input

    cout<<"
Press 1 for yes 0 for No: "<<endl;

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

    {

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

        {

            cout<<vertex[i]<<"->"<<vertex[j]<<": ";

            cin>>graph[i][j];

        }

    }

}

int check(int node)

{

    int i,j;

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

    {

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

        {

            if(graph[i][j] !=1) ///if not connected return 0

            {

                return 0;

            }

        }

    }

    return 1;

}

int main()

{

    int i,j,node;

    cout<<"Please Enter Total Vertex Number: ";

    cin>>node;

    create(node);

    if(check(node) != 0)

    {

     cout<<"
Connected Graph"<<endl;

    }

    else

    {

      cout<<"
Not A Connected Graph"<<endl;

    }

    return 0;

}

Output

Please Enter Total Vertex Number: 4

Press 1 for yes 0 for No:
A->B: 1
A->C:
1
A->D: 1
B->C: 1
B->D: 1
C->D: 1

Join the discussion

Add your comment