这个代码中的DFS与BFS只实现了连通图的深度遍历、广度遍历,详情见
实现图(连通图、非连通图)的深度优先遍历、广度遍历代码
//严蔚敏《数据结构》
//图的遍历:深度优先搜索(DFS)和广度优先搜索(BFS)
//自学中,加油!
#include<iostream>
#include<string>
using namespace std;
#define InfoType double
#define VertexType string
const int MaxVertexNum=20;
typedef struct Edge
{
int ivex;
InfoType* info;
struct Edge* nextedge;
}Edge;//边的邻接点信息
typedef struct VNode
{
VertexType data;
Edge* firstage;
}VNode;//顶点结点
typedef struct
{
VNode Vlist[MaxVertexNum];
int vexnum,edgnum;
int* visited;
}ALGraph;
int Locate_Vlist(ALGraph G,VertexType v)
{
for(int i=0;i!=G.vexnum;i++){
if(G.Vlist[i].data==v)
return i;
}
cout<<"未找到\n";
return -1;
}
bool Creat_UDNGraph(ALGraph& G)//创建无向网的邻接表 bug1:ALGraph G//你这nb啊,心态有点小炸
{
cout<<"输入无向网的顶点数和边数:";
cin>>G.vexnum>>G.edgnum;
G.visited=new int[G.vexnum];
cout<<"输入顶点信息(类型为string)\n";
for(int i=0;i!=G.vexnum;i++){
cin>>G.Vlist[i].data;
G.Vlist[i].firstage=nullptr;
G.visited[i]=0;//0代表未被遍历过
}
VertexType v1,v2;
InfoType w;
int i,j;
Edge* p1,* p2;
for(int k=0;k!=G.edgnum;k++){
cout<<"输入两个顶点信息和权值:";
cin>>v1>>v2>>w;
i=Locate_Vlist(G,v1);
j=Locate_Vlist(G,v2);
p1=new Edge;
if(!p1)
return false;
p1->ivex=j;
p1->info=new InfoType;
*p1->info=w;
p1->nextedge=G.Vlist[i].firstage;G.Vlist[i].firstage=p1;
p2=new Edge;
if(!p2)
return false;
p2->ivex=i;
p2->info=new InfoType;
*p2->info=w;
p2->nextedge=G.Vlist[j].firstage;G.Vlist[j].firstage=p2;
}
return true;
}
void Output_UDN(ALGraph G)//输出无向图的邻接表
{
Edge* p;
for(int i=0;i!=G.vexnum;i++){
cout<<"顶点:"<<G.Vlist[i].data;
p=G.Vlist[i].firstage;
while(p){
cout<<"->邻接点:"<<p->ivex;
if(p->info)
cout<<"权值:"<<*p->info;
p=p->nextedge;
}
cout<<endl;
}
}
void DFS(ALGraph G,int i)//深度优先遍历无向网的邻接表
{
cout<<"信息:"<<G.Vlist[i].data<<endl;
G.visited[i]=1;//遍历过将visited改为1
Edge* p=G.Vlist[i].firstage;
while(p){
if(!G.visited[p->ivex])//若没被遍历过,则对其进行DFS遍历
DFS(G,p->ivex);
p=p->nextedge;
}
}
//构建的队列为图的广度优先遍历服务
#define QElemType int//队列存储边的位置下标
typedef struct QNode
{
QElemType data;
struct QNode* next;
}QNode,* Qlink;
typedef struct
{
Qlink head,tail;
int len;
}LinkQueue;
bool Init_Queue(LinkQueue& Q)//初始化队列
{
Q.head=new QNode;
if(!Q.head)
return false;
Q.head->next=nullptr;
Q.tail=Q.head;
Q.len=0;
return true;
}
bool IsEmpty(LinkQueu