BFS
#include<bits/stdc++.h>
using namespace std;
const int MaxVertexNum=100;
map<char,int> NodeIndex;
bool visited[MaxVertexNum];
typedef struct{
char Vex[MaxVertexNum];
int Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
int FirstNeighbor(MGraph G,char x){
for(int i=0;i<G.vexnum;i++){
if(G.Edge[NodeIndex[x]][i]==1)
return i;
}
return -1;
}
int NextNeighbor(MGraph G,char x,char y){
for(int i=NodeIndex[y]+1;i<G.vexnum;i++){
if(G.Edge[NodeIndex[x]][i]==1)
return i;
}
return -1;
}
void BFS(MGraph G,int idx){
char vex=G.Vex[idx];
cout<<vex<<" ";
visited[idx]=true;
queue<int> Q;
Q.push(idx);
while(!Q.empty()){
vex=G.Vex[Q.front()];
Q.pop();
for(int w=FirstNeighbor(G,vex);w>=0;w=NextNeighbor(G,vex,G.Vex[w])){
if(visited[w]==false){
cout<<G.Vex[w]<<" ";
visited[w]=true;
Q.push(w);
}
}
}
}
void BFSTraverse(MGraph G){
for(int i=0;i<G.vexnum;i++)
visited[i]=false;
for(int i=0;i<G.vexnum;i++){
if(visited[i]==false)
BFS(G,i);
}
}
int main(){
MGraph G;
cout<<"请输入结点总数与边数"<<endl;
cin>>G.vexnum>>G.arcnum;
char vnode;
cout<<"请输入结点名称"<<endl;
for(int i=0;i<G.vexnum;i++){
cin>>vnode;
G.Vex[i]=vnode;
NodeIndex[vnode]=i;
}
char vex1,vex2;
cout<<"请输入相连的结点"<<endl;
for(int i=0;i<G.arcnum;i++){
cin>>vex1>>vex2;
G.Edge[NodeIndex[vex1]][NodeIndex[vex2]]=1;
G.Edge[NodeIndex[vex2]][NodeIndex[vex1]]=1;
}
BFSTraverse(G);
return 0;
}
DFS
#include<bits/stdc++.h>
using namespace std;
const int MaxVertexNum=100;
map<char,int> NodeIndex;
bool visited[MaxVertexNum];
typedef struct{
char Vex[MaxVertexNum];
int Edge[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
int FirstNeighbor(MGraph G,char x){
for(int i=0;i<G.vexnum;i++){
if(G.Edge[NodeIndex[x]][i]==1)
return i;
}
return -1;
}
int NextNeighbor(MGraph G,char x,char y){
for(int i=NodeIndex[y]+1;i<G.vexnum;i++){
if(G.Edge[NodeIndex[x]][i]==1)
return i;
}
return -1;
}
void DFS(MGraph G,int idx){
char vex=G.Vex[idx];
cout<<vex<<" ";
visited[idx]=true;
for(int w=FirstNeighbor(G,vex);w>=0;w=NextNeighbor(G,vex,G.Vex[w])){
if(visited[w]==false)
DFS(G,w);
}
}
void DFSTraverse(MGraph G){
for(int i=0;i<G.vexnum;i++)
visited[i]=false;
for(int i=0;i<G.vexnum;i++){
if(visited[i]==false)
DFS(G,i);
}
}
int main(){
MGraph G;
cout<<"请输入结点总数与边数"<<endl;
cin>>G.vexnum>>G.arcnum;
char vnode;
cout<<"请输入结点名称"<<endl;
for(int i=0;i<G.vexnum;i++){
cin>>vnode;
G.Vex[i]=vnode;
NodeIndex[vnode]=i;
}
char vex1,vex2;
cout<<"请输入相连的结点"<<endl;
for(int i=0;i<G.arcnum;i++){
cin>>vex1>>vex2;
G.Edge[NodeIndex[vex1]][NodeIndex[vex2]]=1;
G.Edge[NodeIndex[vex2]][NodeIndex[vex1]]=1;
}
DFSTraverse(G);
return 0;
}