mercredi 30 octobre 2019

How to Fix This error while running this DFS code?

I have written a code to implement dfs on a graph as follows:

#include <iostream>
#include<stack>
#include<stdbool.h>
#define MAX 10
using namespace std;
int vertex_id=0;
int graph_id=0;
class vertex{
    public:
    int id;
    int visited;
    int adj[MAX];
    vertex();
};
vertex::vertex()
{
    visited=0;
    id=++vertex_id;
    for(int i=0;i<MAX;i++)
    {
        adj[i]=0;
    }
}
class graph:public vertex{
    public:
    stack<vertex> s;
    int g_id;
    vertex adj_matrix[MAX+1][MAX+1];
    void dfs(vertex v);
    void show_dfs(vertex v);
    void add_edge(vertex v1,vertex v2);
    graph();
};
graph::graph(){
    g_id=graph_id++;    //for multiple graphs
    vertex_id=0;
    for(int i=1;i<MAX+1;i++)
    {
        for(int j=1;j<MAX+1;j++)
        {
            adj_matrix[i][j].id=-1;
        }
    }
}
void graph::add_edge(vertex v1,vertex v2){
    v1.adj[v2.id]=1;
    v2.adj[v1.id]=1;
    adj_matrix[v1.id][v2.id]=v2;
    adj_matrix[v2.id][v1.id]=v1;
}
void graph::dfs(vertex v){
    s.push(v);
    v.visited=true;
    int counter=0;
    for(int i=1;i<MAX+1;i++)
    {
        if(adj_matrix[v.id][i].visited==0 && adj_matrix[v.id][i].id!=-1)
        {
            adj_matrix[v.id][i].visited=1;
            counter=1;  //successfully found adjacent unvisited vertex
            vertex va=adj_matrix[v.id][i];
            dfs(va);
            return;         //once dfs is excecuted, no breadth traversal should follow
        }
    }
    if(!counter)
    {
        show_dfs(v);
        cout<<endl;
        return;
    }
}
void graph::show_dfs(vertex v){
        if(s.empty())
        cout<<"No Paths Found ";
        while(!s.empty())
        {
            cout<<(s.top()).id<<"<---";
            s.pop();
        }
}
int main()
{
    graph g;
    vertex v1,v2,v3,v4,v5,v6,v7,v8,v9,v10;
    g.add_edge(v1,v2);
    g.add_edge(v1,v3);
    g.add_edge(v1,v5);
    g.add_edge(v3,v4);
    g.add_edge(v3,v2);
    g.add_edge(v2,v8);
    g.add_edge(v8,v9);
    g.add_edge(v9,v10);
    g.add_edge(v5,v7);
    g.add_edge(v5,v6);
    g.add_edge(v6,v7);
    g.dfs(v2);
    //g.show_dfs(v2);
    return 0;
}

The problem with my code is although it compiles without error but it keeps on pushing the same vertices more than once even when the visited attribute is made true and is checked for each time the loop runs. for example the graph used here produces the following output: Sample output

Aucun commentaire:

Enregistrer un commentaire