图形BFS遍历-C++



给定一个无向且不连通的图G(V,E(,打印其BFS遍历。这里需要考虑的是,您需要打印仅从顶点0开始的BFS路径。V是图G中存在的顶点的数量,并且顶点的编号从0到V-1。E是图G中存在的边的数量。注:1。在邻接矩阵中输入图形。2.断开图的句柄输入格式:第1行:两个整数V和E(用空格分隔(接下来的"E"行,每行都有两个空格分隔的整数,"a"one_answers"b",表示顶点"a"与顶点"b"之间存在边。输出格式:BFS导线(用空格分隔(限制条件:2<=V<=10001<=E<=1000样本输入1:4 40 10 31 22 3样本输出1:0 1 3 2请说出代码中的错误。

这是代码:

#include <iostream>
using namespace std;
#include <queue>
void print(int** edges, int V, int sv, bool* visited){
queue<int> pq;
pq.push(sv);
visited[sv] = true;
while(!pq.empty()){
int ans = pq.front();
cout << ans << " ";
pq.pop();
for(int i = 0; i < V; i++){
if(ans == i){
continue;
}
if(edges[ans][i] == 1 && !visited[i]){
pq.push(i);
visited[i] = true;
}
}
}
}   
void BFS(int** edges, int V){
bool* visited = new bool[V];
for(int i = 0; i < V; i++){
visited[i] = false;
}
for(int i = 0; i < V; i++){
if(!visited[i]){
print(edges, V, i, visited);
}
}
delete [] visited;
}



int main() {
int V, E;
cin >> V >> E;
int**edges = new int*[V];
for(int i = 0; i < V; i++){
edges[i] = new int[V];
for(int j = 0; j < V; j++){
edges[i][j] = 0;
}
}
for(int i = 0; i < E; i++){
int f, s;
cin >> f >> s;
edges[f][s] == 1;
edges[s][f] == 1;
}

BFS(edges, V);
for(int i = 0; i < V; i++){
delete [] edges[i];
}
delete [] edges;
/*
Write Your Code Here
Complete the Rest of the Program
You have to take input and print the output yourself
*/

}

我认为唯一的问题是我在您从命令行读取params的部分中看到的一个小错误。算法本身看起来不错。读取边缘时,需要使用赋值运算符=而不是比较运算符==

edges[f][s] = 1;
edges[s][f] = 1;

最新更新