c++ - 邻接矩阵上的 BFS

标签 c++ breadth-first-search

我正在尝试在无向未加权图的邻接矩阵上实现 BFS,它返回访问的节点数。到目前为止,我已经想到了这个,但我认为这是不正确的,因为当我打印出顶部/访问过的节点时,我得到了一些节点的多次出现,而且它没有排序。我在某处读到 BFS 是一种拓扑排序,我得到的顺序没有排序。

int BFS(std::vector<std::vector<int> > &matrix, int start)
{
    std::vector<bool> visited(matrix.size(), false);
    std::queue<int> Q;
    Q.push(start);
    int count = 0;

    while( ! Q.empty())
    {
        int top = Q.front(); Q.pop();
        visited[top] = true; count++;
        for (int i = 0; i < matrix.size(); ++i)
        {
            if(matrix[top][i] != 0 && (! visited[i]) )
            {
                Q.push(i);
            }
        }
    }
    return count;
}

最佳答案

不是在弹出队列后将visited节点设置为true,而是在将其插入队列时设置它,并在里面添加计数,以防止某些节点重复计数。请引用以下内容:

//..previous lines

Q.push(start);
visited[start] = true;
int count = 1;

while(!Q.empty()){
    int top = Q.front(); Q.pop();

    for (int i = 0; i < matrix.size(); ++i){
        if(matrix[top][i] != 0 && (! visited[i]) ){
            Q.push(i);
            visited[i] = true;
            count++;
        }
    }
}

关于c++ - 邻接矩阵上的 BFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36899181/

相关文章:

c++ - 模板和非模板函数的意外输出

c++ - 在不同线程中启动服务器和 IHM

algorithm - DFS 和 BFS 可以互换吗?

算法 : Difference of output tree as subgraph from DFS and BFS

java - 深度优先搜索给出错误的输出

Python广度优先搜索矩阵打印路径

c++ - 一个类应该能够输出其内容还是另一个类应该这样做?

C++:传递给 C 运行时函数的参数无效

c++ - 是什么导致了这种格式字符串攻击?

python - 实现具有最大深度并打印所有最短路径的 BFS 算法