Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Depth first search (C++)

I've created a class that contains a vector of Linked Lists. Each Linked List represents a vertice in my graph. The Nodes connected to my linked lists are considered the edges between these vertices. I'm trying to create a DFS function for my graph, but am having trouble with setting the colors of my vertices. I realize there are a lot of problems with my code, but i'm trying to solve one in particular. My DFSit() function ends up in an infinite loop because the color attribute for my list isn't actually getting set to "gray". Any idea why this would be?

void Graph::DFS()
{
    int i = 0;
    while (i != myvector.size())
    {

        DFSit(myvector[i], myvector[i].val);
        myvector[i].color = "black";
        i++;
    }
}

void Graph::DFSit(AdjList x, int root)
{
if (x.color == "white")
{
    cout << "tree edge ( " << root << "," << x.val << ") " << endl;
}
if (x.color == "gray")
{
    cout << "Back Edge ( " << root << "," << x.val << ") " << endl;
    return;
}

    x.color = "gray";

    AdjNode *temp = new AdjNode();
    temp = x.front;
    int i = 0;
    int value;
    while (temp != NULL)
    {
        value = temp->getValue();
        while (i != myvector.size())
        {
            if (value == myvector[i].val)
            {
                DFSit(myvector[i], root);
            }
            i++;
        }
        temp = temp->next;
    }

}
like image 787
user2796815 Avatar asked Jun 10 '26 17:06

user2796815


1 Answers

Normaly, the proper implementation of the DFS rutine is made with a stack, but this could work also. I think that you are coloring the node AdjList x and this coloring is not save because you are passing it by val and not by ref. try changing void Graph::DFSit(AdjList x, int root) into void Graph::DFSit(AdjList& x, int root)

like image 135
Idan Yehuda Avatar answered Jun 12 '26 10:06

Idan Yehuda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!