Solved programming problem

Insert an Graph and Print all vertex where we can visit from one node in C++.

Source code

#include <iostream>

using namespace std;

int main()

{

    int graph[100][100];

    char vertex[26];

    int i,j,node;

    ///Create all vertex

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

    {

        vertex[i]=65+i;

    }

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

    cin>>node;

    ///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];

            if(graph[i][j]==1) ///if input is 1

            {

                graph[j][i]; /// make the duplicate node 1  like if A->B is 1 make B->A =1

            }

        }

    }

    ///print all node we can visit from each vertex

    cout<<"All node of Your Graph: "<<endl;

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

    {

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

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

        {

            if(graph[i][j]==1 || graph[j][i]==1)

            {

                cout<<vertex[j]<< " ";

            }

        }

        cout<<endl;

    }

    return 0;

}

Output

Please Enter Total Vertex Number: 4

Press 1 for yes 0 for No:
A->B: 1
A->C: 0
A->D: 1
B->C: 1
B->D: 0
C->D: 1
All node of Your Graph:
A-> B D
B-> A C
C-> B D
D-> A C

Join the discussion

Add your comment