用广搜搜邻接矩阵
只是从某一点开始搜,如果是遍历全图的话就每个顶点挨个搜一遍
#include<stdio.h>
#include<string.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<queue>
#define inf 65535
using namespace std;
typedef struct mygraph
{
int ver[1000];
int arc[100][100];
int num_ver,num_edge;
} Graph;
int vis[100];
void create(Graph *G)//邻接矩阵建图
{
int i,j,k;
scanf("%d%d",&G->num_ver,&G->num_edge);//输入节点数和边数
for(i=0; i<G->num_ver; i++)//输入边集
scanf("%d",&G->ver[i]);
for(i=0; i<G->num_ver; i++)//权值初始化
{
for(j=0; j<G->num_edge; j++)
G->arc[i][j]=inf;
}
int a,b,c;
for(i=0; i<G->num_edge; i++)//输入边集
{
scanf("%d%d%d",&a,&b,&c);
G->arc[a][b]=c;
G->arc[b][a]=c;
}
}
queue<int>q;
void bfs(Graph *g,int x)//广搜
{
int i,tmp,tmp1,tmp2;
while(!q.empty())q.pop();
q.push(x);
vis[x]=1;
while(!q.empty())
{
tmp=q.front();
printf("%d",tmp);
q.pop();
for(i=0; i<g->num_ver; i++)
{
if(!vis[i]&&g->arc[tmp][i]!=inf)
{
q.push(i);
vis[i]=1;
}
}
}
}
int main()
{
int i,j,k;
Graph myG;
create(&myG);
memset(vis,0,sizeof(vis));
bfs(&myG,0);
printf("\n");
// for(i=0; i<myG.num_ver; i++)//打印邻接矩阵
// {
// for(j=0; j<myG.num_ver; j++)
// printf("%5d ",myG.arc[i][j]);
// printf("\n");
// }
return 0;
}
/*
5 6
0 1 2 3 4
0 1 9
0 2 2
0 4 6
1 2 3
2 3 5
3 4 1
*/
测试数据中5 6代表节点数为5,边数为,6,下面是结点名0 1 2 3 4 下面几行中分别为为 弧尾(边的起点),弧首(边的终点),和边的权值