图的深度优先和广度优先遍历(图以邻接表表示,由C++面向对象实现)

时间:2023-03-10 02:08:09
图的深度优先和广度优先遍历(图以邻接表表示,由C++面向对象实现)

学习了图的深度优先和广度优先遍历,发现不管是教材还是网上,大都为C语言函数式实现,为了加深理解,我以C++面向对象的方式把图的深度优先和广度优先遍历重写了一遍。

废话不多说,直接上代码:

 #include<iostream>

 using namespace std;

 //构造一个循环队列来存放广度优先算法的下标

 #define ADD 5;

 using namespace std;

 class CirQueue
{
private:
int * base;
int front,rear,size,length;
public:
bool InitCirQueue(int size)
{
this->size=size;
base=new int[size];
if(!base)
{
return false;
}
front=rear=length=;
return true;
}
bool insertQueue(int num)
{
if(length==size)
{
int newsize=size+ADD;
int * newbase=new int[newsize];
if(!newbase)
{
return false;
}
int i=;
for(i=;i<length;i++)
{
newbase[(front+i)%newsize]=base[(front+i)%size];
}
rear=(front+i)%newsize;
base=newbase;
size=newsize;
}
base[rear]=num;
rear=(rear+)%size;
++length;
return true;
}
int outQueue()
{
int temp=base[front];
front=(front+)%size;
--length;
return temp;
}
void traverseQueue()
{
for(int i=;i<length;i++)
{
cout<<base[(front+i)%size]<<endl;
}
}
int getLength()
{
return length;
}
bool isEmpty()
{
if(==length)
{
return true;
}
else
{
return false;
}
}
bool isFull()
{
if(length==size)
{
return true;
}
else
{
return false;
}
}
}; // void main()
// {
// CirQueue cq;
// cq.InitCirQueue(5);
// for(int i=1;i<=100;i++)
// {
// cq.insertQueue(i);
// }
// cq.traverseQueue();
// } //构造循环队列结束 struct Arc
{
int adjvex;
Arc * next;
}; struct Vertex
{
char data;
Arc * firstarc;
}; class Map
{
private:
Vertex * vexList;
int vexNum;
int arcNum;
bool * visted;
public:
Map(int vexNum,int arcNum)
{
this->vexNum=vexNum;
this->arcNum=arcNum;
visted=new bool[vexNum];
for(int i=;i<vexNum;i++)
{
visted[i]=false;
}
vexList=new Vertex[vexNum];
for(int i=;i<vexNum;i++)
{
cout<<"请输入第"<<i<<"个顶点的数据:";
cin>>vexList[i].data;
vexList[i].firstarc=NULL;
}
for(int i=;i<arcNum;i++)
{
int a,b;
cout<<"请输入第"<<i+<<"条边的两顶点";
cin>>a>>b; Arc * tempArc=new Arc;
tempArc->adjvex=b;
tempArc->next=vexList[a].firstarc;
vexList[a].firstarc=tempArc; //因为是无向图所以是双向的
tempArc=new Arc;
tempArc->adjvex=a;
tempArc->next=vexList[b].firstarc;
vexList[b].firstarc=tempArc;
}
}
void DFS(int v)
{
cout<<vexList[v].data<<endl;
visted[v]=true;
Arc * p=vexList[v].firstarc;
while(p)
{
int u=p->adjvex;
if(!visted[u])
{
DFS(u);
}
p=p->next;
}
}
void BFS(int v)
{
CirQueue cq;
cq.InitCirQueue();
cout<<vexList[v].data<<endl;
visted[v]=true;
cq.insertQueue(v);
while(!cq.isEmpty())
{
v=cq.outQueue();
Arc * p=vexList[v].firstarc;
while(p)
{
int j=p->adjvex;
if(!visted[j])
{
cout<<vexList[j].data<<endl;
visted[j]=true;
cq.insertQueue(j);
}
p=p->next;
}
}
}
void ClearVisted()
{
for(int i=;i<vexNum;i++)
{
visted[i]=false;
}
}
}; int main()
{
Map map(,);
cout<<"--------------深度优先遍历————————————————"<<endl;
map.DFS();
map.ClearVisted();
cout<<"--------------广度优先遍历————————————————"<<endl;
map.BFS();
return ;
}

运行结果为:

图的深度优先和广度优先遍历(图以邻接表表示,由C++面向对象实现)