Question

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;
    }

}
Was it helpful?

Solution

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top