Graph 用BFS求无向图的圈
我想只使用BFS(而不是DFS)在无向图中查找第一个循环。所有来源都用DFS解决了这个问题,但我必须用BFS找到它。我怎样才能找到它?提前谢谢 在下面,您将找到使用BFS遍历图形并找到其循环的代码。Graph 用BFS求无向图的圈,graph,cycle,breadth-first-search,undirected-graph,Graph,Cycle,Breadth First Search,Undirected Graph,我想只使用BFS(而不是DFS)在无向图中查找第一个循环。所有来源都用DFS解决了这个问题,但我必须用BFS找到它。我怎样才能找到它?提前谢谢 在下面,您将找到使用BFS遍历图形并找到其循环的代码。 #include <stdio.h> #include <queue> using namespace std; int nodes, edges, src; int graph[100][100], color[100], prev[100]; const int WHI
#include <stdio.h>
#include <queue>
using namespace std;
int nodes, edges, src;
int graph[100][100], color[100], prev[100];
const int WHITE = 0;
const int GRAY = 1;
const int BLACK = 2;
void print(int);
int main() {
printf("Nodes, edges, source? ");
scanf("%d %d %d ", &nodes, &edges, &src);
for(int i = 1; i <= edges; i++) {
printf("Edge %d: ", i);
int x, y;
scanf("%d %d", &x, &y);
graph[x][y] = 1;
}
//run BFS
queue<int> q; //create a queue
q.push(src); //1. put root node on the queue
do{
int u = q.front(); //2. pull a node from the beginning of the queue
q.pop();
printf("%d ", u); //print the node
for(int i = 1; i <= nodes; i++) { //4. get all the adjacent nodes
if((graph[u][i] == 1) //if an edge exists between these two nodes,
&& (color[i] == WHITE)) { //and this adjacent node is still WHITE,
q.push(i); //4. push this node into the queue
color[i] = GRAY; //color this adjacent node with GRAY
}
}
color[u] = BLACK; //color the current node black to mark it as dequeued
} while(!q.empty()); //5. if the queue is empty, then all the nodes havebeen visited
//find and print cycle from source
for(int i = 1; i <= nodes; i++) {
if(graph[i][src] == 1) {
print(i);
printf("%d\n\n", src);
}
}
return 0;
}
void print(int node) {
if(node == 0)
return;
print(prev[node]);
printf("%d -> ", node);
}
#包括
#包括
使用名称空间std;
int节点、边、src;
int图形[100][100],颜色[100],上一个[100];
常数int白色=0;
常数int GRAY=1;
常数int BLACK=2;
空白打印(int);
int main(){
printf(“节点、边、源?”);
scanf(“%d%d%d”、&nodes、&edges、&src);
对于(int i=1;我请在您的答案顶部添加一些细节。