Sunday, 10 September 2017

Implementation of any 2 uninformed search methods with some application.

CODE :

#include<iostream>
#include <list>

using namespace std;

class Graph
{
    int vertices; 
    list<int> *ptr;
    void DFSUtil(int vertex, bool visited[]);
public:
    Graph(int vertices); 
    void addEdge(int vertex1, int vertex2);
    void BFS(int start_vertex);
    void DFS(int start_vertex); 
};

Graph::Graph(int vertices)
{
    this->vertices = vertices;
    ptr = new list<int>[vertices];
}

void Graph::addEdge(int vertex1, int vertex2)
{
    ptr[vertex1].push_back(vertex2);
}

void Graph::BFS(int start_vertex)
{
    bool *visited = new bool[vertices];
    for(int i = 0; i < vertices; i++)
        visited[i] = false;

    list<int> queue;
   
    visited[start_vertex] = true;
    queue.push_back(start_vertex);

    list<int>::iterator itr;

    while(!queue.empty())
    {
        start_vertex = queue.front();
        cout << start_vertex << " ";
        queue.pop_front();

        for(itr = ptr[start_vertex].begin(); itr != ptr[start_vertex].end(); ++itr)
        {
            if(!visited[*itr])
            {
                visited[*itr] = true;
                queue.push_back(*itr);
            }
        }
    }
}

void Graph::DFSUtil(int start_vertex, bool visited[])
{
    visited[start_vertex] = true;
    cout << start_vertex << " ";

    list<int>::iterator itr;
    for (itr = ptr[start_vertex].begin(); itr != ptr[start_vertex].end(); ++itr)
        if (!visited[*itr])
            DFSUtil(*itr, visited);
}

void Graph::DFS(int start_vertex)
{
    bool *visited = new bool[vertices];
    for (int i = 0; i < vertices; i++)
        visited[i] = false;
    DFSUtil(start_vertex, visited);
}
 
 
int main()
{
    int no_vertices,start_vertex;
    cout<<"Enter the number of vertices"<<endl;
    cin>>no_vertices;
    int matrix[no_vertices][no_vertices];
    Graph gr(no_vertices);
    cout<<"\n\nEnter Adjacency Matrix of size ["<<no_vertices<<"x"<<no_vertices<<"]: \n"; 
    for(int i=0;i<no_vertices;i++) 
    { 
        for(int j=0; j<no_vertices; j++) 
        { 
            cin>>matrix[i][j]; 
        } 
    }
   
    for(int i=0; i<no_vertices; i++) 
    {            
        for(int j=0; j<no_vertices; j++) 
        { 
            if(matrix[i][j] == 1) 
            { 
                gr.addEdge(i,j); 
            } 
        } 
    }
     
    cout<<"Enter start vertex"<<endl;
    cin>>start_vertex;
    cout<<"BFS"<<endl;
    gr.BFS(start_vertex);
    cout<<"\nDFS"<<endl;
    gr.DFS(start_vertex);
    return 0;
}


OUTPUT :


No comments:

Post a Comment