目录
原题复刻
思想的火花
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);
}