代码:
#include<iostream>
using namespace std;
struct node{
int a;
node *next;
};
typedef struct node1{
char s;
node *f;
}node1,st[110];
struct node2{
st ss;
int vm,vn;
};
struct que{
int *b;
int f,r;
};
void Bque(que &Q){
Q.b = new int[100];
Q.f = Q.r = 0;
}
void Ique(que &Q,int a){
if((Q.r + 1) % 100 == Q.f) return ;
Q.b[Q.r] = a;
Q.r = (Q.r + 1) % 100;
}
bool Eque(que &Q){
if(Q.r == Q.f) return true;
return false;
}
int Dque(que &Q){
int a = Q.b[Q.f];
Q.f = (Q.f + 1) % 100;
return a;
}
int vis[110],viss[110];
int fd(char s,node2 G){
for(int i = 0; i < G.vm; i++)
if(G.ss[i].s == s)
return i;
return -1;
}
void bulid(node2 &G){
cout << "输入总的定点数和边数: " << endl;
cin >> G.vm >> G.vn;
cout << "依次输入顶点名称(空格隔开):" << endl;
for(int i = 0; i < G.vm;i++)
cin >> G.ss[i].s,G.ss[i].f = NULL;
cout << "依次输入每条边链接的两个点(空格隔开):" << endl;
for(int i = 0; i < G.vn; i++){
char s1,s2;
cin >> s1 >> s2;
int m1 = fd(s1,G),m2 = fd(s2,G);
node *p = new node;
p -> a = m2;
p -> next = G.ss[m1].f;
G.ss[m1].f = p;
node *p1 = new node;
p1 -> a = m1;
p1 -> next = G.ss[m2].f;
G.ss[m2].f = p1;
}
}
void DFS(node2 G,int a){
cout << G.ss[a].s << " ";
node *p = G.ss[a].f;
while(p){
if(!vis[p -> a])
vis[p -> a] = 1,DFS(G,p -> a);
p = p -> next;
}
}
void BFS(node2 G,int a){
que Q;
cout << G.ss[a].s << " ";
Bque(Q);
Ique(Q,a);
while(!Eque(Q)){
int o = Dque(Q);
node *p = G.ss[o].f;
while(p){
if(!viss[p -> a]) viss[p -> a] = 1,cout << G.ss[p -> a].s << " ",Ique(Q,p -> a);
p = p -> next;
}
}
}
int main()
{
node2 G;
bulid(G);
cout << "输入合法起点 :" << endl;
char c; cin >> c;
int o;
for(int i = 0; i < G.vm; i++)
if(G.ss[i].s == c){
o = i; break;
}
cout << "DFS 遍历结果为 :" << endl;
vis[o] = 1;
DFS(G,o);
cout << endl;
cout << "BFS 遍历结果为 :" << endl;
viss[o] = 1;
BFS(G,o);
return 0;
}