#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
struct Node{
//to 代表每个节点
//next 代表下一个元素的编号
int to,next;
}e[100];
int head[100] = {0};
int cnt = 0;
//暂时存储待遍历点
queue<int> q;
//做标志
bool vis[100] = {false};
//建立邻接表
void add(int a,int b){
//cnt 用于记录每个点的编号
cnt++;
//a 的邻接表头插入 b
e[cnt].next = head[a];
e[cnt].to = b;
//头插入后 将a邻接表的头的编号修改
head[a] = cnt;
}
//广度优先搜索
void BFS(int n){
vis[n] = true;//主要针对第一个元素
//遍历 n 列表对应的邻接表
for(int i = head[n];i != 0;i = e[i].next){
if(vis[e[i].to] == false){
q.push(e[i].to);//当这个节点没有被访问过 则 入队
vis[e[i].to] = true;//标志节点被访问了
}
}
}
void BFSTraver(int ft){
//搜索开始的节点ft
q.push(ft);
while (!q.empty()) {
cout << q.front() << " ";
BFS(q.front());
//遍历q.front()所对应的邻接表后 就删除
q.pop();
}
}
int main(int argc, char const *argv[]) {
//N->几条路径
int N;
printf("please input the number of rode:");
scanf("%d",&N);
printf("please input every rode:\n");
for(int i = 0;i < N;i++){
int a,b;
scanf("%d%d",&a,&b);
//创建邻接表
add(a,b);
add(b,a);
}
// for(int i = 1;i <= N;i++){
// for(int j = head[i];j != 0;j = e[j].next){
// printf("%d ",e[j].to);
// }
// printf("\n");
// }
printf("please input the first point:");
//遍历的第一个节点
int ft;
scanf("%d",&ft);
printf("BFS:\n");
BFSTraver(ft);
printf("\n");
return 0;
}
广度优先搜索(邻接表)
猜你喜欢
转载自blog.csdn.net/WX_1218639030/article/details/83829838
今日推荐
周排行