Solved programming problem

BFS in C++.

Source code

#include <iostream>

#include<stdlib.h> ///for use rand function on c++

#define size 100

using namespace std;

int f=0,r=0,n;

char q[size + 1];

char visit_array[100];

int len=0;

char vertex[26];

int graph[100][100];

void visit(char ch) ///save the visited node

{

    visit_array[len]=ch;

    len++;

}

int is_visit(char ch) ///check if the node is already visited or not

{

    for(int i=0; i<len; i++)

    {

        if(ch == visit_array[i])

        {

            return 1;

        }

    }

    return 0;

}

void enqueue(char ch) /// enqueue function

{

    r = (r+1)%(size+1);

    q[r] = ch;

}

void print_visit_array() ///print

{

    for(int i=0; i<len; i++)

    {

        cout<<visit_array[i]<<" ";

    }

}

char dequeue()/// dequeue function

{

    f = (f+1)%(size+1);

    char ch = q[f];

    q[f] = '';

    return ch;

}

void find_adj(char ch) ///find all the connected node

{

    for(int i=0; i<n; i++)

    {

        for(int j=0; j<n; j++)

        {

            if(graph[i][j]==1 && vertex[i]==ch)

            {

                if(is_visit(vertex[j])==0) ///check if the node is visited or not

                {

                    enqueue(vertex[j]); ///send it two the array

                }

            }

        }

    }

}

void BFS()

{

    enqueue(vertex[0]); ///make the 1st node A as root node

    while(f!=r) /// while the queues is not empty

    {

        char v = dequeue(); ///dequeue

        find_adj(v); ///find its adjacent list node

        if(is_visit(v)==0)

        {

            visit(v); ///send it to the visit array

        }

    }

}

void create() ///create the graph

{

    int i,j;

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

    {

        vertex[i]=65+i;

    }

    cout<<"Enter Total Vertex Number: ";

    cin>>n;

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

    {

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

        {

            graph[i][j]=0;

        }

    }

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

    {

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

        {

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

            cin>>graph[i][j];

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

            {

                graph[j][i]=1;

            }

        }

    }

}

int main()

{

    create();

    BFS();

    cout<<"
B F S: ";

    print_visit_array();

    cout<<endl;

    return 0;

}

Output

Enter Total Vertex Number: 4
AB :1
AC :1
AD :0
BC :0
BD :1
CD :1

B F S: A B C D

Join the discussion

Add your comment

1 previous comment

abc

give some more codes sir.