目录
原题复刻

思想的火花
1.bfs(运用自带库函数queue)
void bfs(graph &g,int v)
{
cout<<v<<" ";
vis[v]=1;
q.push(v);
int u;
while(!q.empty())
{
u=q.front();
q.pop();
for(int w=firstadjves(g,u); w>=0; w=nextadjves(g,u,w))
{
if(!vis[w])
{
cout<<w<<" ";
vis[w]=1;
q.push(w);
}
}
}
}
代码实现
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
typedef int VerTexType,qelemtype;
typedef int Arctype,status;
typedef struct
{
VerTexType vexs[MAX];
Arctype arcs[MAX][MAX];
int vexnum,arcnum;
} graph;
VerTexType vertexdata(const graph &g,int i)
{
return g.vexs[i];
}
int firstadjves(const graph &g,int v)
{
for(int j=0; j<g.vexnum; j++)if(g.arcs[v][j]==1)return j;
return -1;
}
int nextadjves(const graph &g,int v,int w)
{
for(int i=w+1; i<g.vexnum; i++)if(g.arcs[v][i]==1)return i;
return -1;
}
void createudg(graph &g)
{
cin>>g.vexnum;
for(int i=0; i<g.vexnum; i++)
{
for(int j=0; j<g.vexnum; j++)cin>>g.arcs[i][j];
}
}
bool vis[MAX];
queue<int>q;
void bfs(graph &g,int v)
{
cout<<v<<" ";
vis[v]=1;
q.push(v);
int u;
while(!q.empty())
{
u=q.front();
q.pop();
for(int w=firstadjves(g,u); w>=0; w=nextadjves(g,u,w))
{
if(!vis[w])
{
cout<<w<<" ";
vis[w]=1;
q.push(w);
}
}
}
}
int main()
{
graph g;
createudg(g);
bfs(g,0);
}
该博客介绍了如何利用BFS(广度优先搜索)算法遍历无向图,并给出了C++的代码实现。首先定义了图的数据结构,然后通过`createudg`函数读取图的边信息。`bfs`函数中,使用队列进行节点的访问,并通过`firstadjves`和`nextadjves`函数获取相邻节点,确保所有未访问过的节点都被遍历。
1519

被折叠的 条评论
为什么被折叠?



