#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<queue>
using namespace std;
#define maxvalue 32700
typedef struct{
char vexlist[100];
int edge[100][100];
int n,e;
}graph;
int vis[100];
void dfs(graph g,int v){
vis[v]=1;
cout<<v<<" ";
for(int i=1;i<=g.n;i++){
if(vis[i]==0&&g.edge[v][i]<maxvalue) dfs(g,i);
}
}
void bfs(graph g,int v){
queue<int>q;
vis[v]=1;
q.push(v);
while(!q.empty()){
int s=q.front();
q.pop();
cout<<s<<" ";
for(int i=1;i<=g.n;i++){
if(vis[i]==0&&g.edge[s][i]<maxvalue){q.push(i);
vis[i]=1;}
}
}
}
int main()
{
graph g;
int s,t,path;
cout<<"请输入顶点个数"<<endl;
cin>>g.n;
cout<<"请输入边数"<<endl;
cin>>g.e;
for(int i=1;i<=g.n;i++){
for(int j=1;j<=g.n;j++){
g.edge[i][j]=maxvalue;
}
}
cout<<"请输入各边权值"<<endl;
for(int i=1;i<=g.e;i++){
cin>>s>>t>>path;
g.edge[s][t]=path;
}
for(int i=1;i<=g.n;i++)
vis[i]=0;
dfs(g,1);
cout<<endl;
for(int i=1;i<=g.n;i++)
vis[i]=0;
bfs(g,1);
cout<<endl;
}
图的深度优先遍历和广度优先遍历
最新推荐文章于 2021-07-28 10:56:03 发布