代码:
#include<iostream>
using namespace std;
int vis[110];
struct node{
int a;
node *next;
};
typedef struct node1{
char s;
node *f;
}st[110];
struct node2{
st ss;
int vn,vm;
};
struct sta{
int *s;
int f,e;
};
void Bsta(sta &S){
S.s = new int[110];
S.f = S.e = 0;
}
void Ista(sta &S,int a){
if((S.e + 1) % 110 == S.f) return ;
S.e = (S.e + 1) % 110;
S.s[S.e] = a;
}
bool Esta(sta &S){
if(S.f == S.e) return true;
return false;
}
int Dsta(sta &S){
int a = S.s[S.e--];
return a;
}
int w(node2 G,char s){
for(int i = 1; i <= G.vn; i++)
if(G.ss[i].s == s)
return i;
}
void bd(node2 &G){
cout << "输入总的顶点数和边数" << endl;
cin >> G.vn >> G.vm;
cout << "依次输入顶点名称" << endl;
for(int i = 1; i <= G.vn; i++)
cout << "第" << i << "顶点的名称是" << endl,cin >> G.ss[i].s,G.ss[i].f = NULL;
cout << "依次输入每条边连接的两个点" << endl;
for(int i = 1; i <= G.vm; i++){
char a,b;
cout << "\n第" << i << "条边连接两个点为";
cin >> a >> b;
int ma = w(G,a),mb = w(G,b);
node *p = new node;
p -> a = mb;
p -> next = G.ss[ma].f;
G.ss[ma].f = p;
p = new node;
p -> a = ma;
p -> next = G.ss[mb].f;
G.ss[mb].f = p;
}
}
void BFS(node2 G,int a){
sta S;
cout << G.ss[a].s << " ";
Bsta(S);
Ista(S,a);
while(!Esta(S)){
int o = Dsta(S);
node *p = G.ss[o].f;
int ok = 0;
while(p && vis[p -> a]) p = p -> next;
if(!p) continue;
int b = p -> a;
p = p -> next;
if(p)
Ista(S,o),G.ss[o].f = p;
cout << G.ss[b].s << " ",vis[b] = 1,Ista(S,b);
}
}
int main(){
node2 G;
bd(G);
cout << "输入合法起点" << endl;
char c;
cin >> c;
int mc = w(G,c);
cout << "BFS遍历结果" << endl;
vis[mc] = 1;
BFS(G,mc);
return 0;
}