BFS树有空输出。可能有什么不对?

时间:2016-08-17 05:34:24

标签: c++

我正在尝试实现BFS算法。它应该将图形作为输入。然后输出应该是BFS树。它也应该跟踪父母和水平。我试图遵循维基百科的伪代码。但是,我得到一个空的BFS树。哪个部分我做错了以及如何修复它?谢谢。以下是代码段:

Graph Bicc::breadthFirstSearch(Graph& sparseGraph) {
    Graph tree;

    Vertex root = sparseGraph.getVertex(0);
    Vertex parent(-1);
    root.parent = &parent; 
    root.color = "white";
    root.level = 0;

    for(size_t i = 0; i < sparseGraph.getVertexCount(); i++){
        sparseGraph.getVertex(i).color = "white";
    }

    queue<Vertex> q;
    list<Vertex> neighbors = root.getNeighbors();
    root.color = "gray";
    q.push(root);                   

    while(!q.empty())
    {
        root = q.front();
        q.pop();

        for(auto& neighbor : neighbors)
        {
            if(neighbor.color == "white")
            {
                neighbor.color = "gray";
                neighbor.level = neighbor.level + 1;
                Vertex n_parent(0);
                neighbor.parent = &n_parent + 1;
                q.push(neighbor);
                tree.add(neighbor);
            }
        }
    }
    return tree;
}

0 个答案:

没有答案