本来打算在数据结构的 练习9 继续写此篇的,以保持连贯性,后来发现,没法写,因为BFS的优先队列,没接触过,只能回头学了,翻开《算法导论》,发现优先队列有堆实现,而堆又不会,牵一发而动全身啊,没办法,只能学了,直接看MIT的《算法导论》视频吧,看看最基本的排序算法,反正早晚要复习到。
7月9号接着写。上一篇博文《数据结构-练习 9 图的存储》介绍了图的存储方式之一,邻接链表。在这里将介绍图的遍历,包括深度优先和广度优先。
上代码:
/*coder information:
e_mail:shenganbeiyang@163.com
QQ:501968942@qq.COM
*/
#include<iostream>
#include<queue>
using namespace std;
struct edgeNode;
/*
define the struct
*/
//定义数据结构
struct DataNode
{
char savedData;
//int weight;the weight of node
edgeNode* next;
DataNode()
{
savedData='\0';
next=NULL;
}
};
struct edgeNode
{
int sequence;//存放数组的下标,表示数据之间的关系
edgeNode* next;
};
//节点数目
const int NUM=7;
DataNode GraphList[NUM];
int visited[NUM];
queue<int> que_DN;
//建立图
void createGraph(DataNode * graphl)
{
cout<<"请输入7个数据节点:"<<endl;
char inputChar;
int nodeOne;
int nodeTwo;
for(int i=0;i<NUM;++i)
{
cin>>inputChar;
graphl[i].savedData=inputChar;
}
//建立 边
cout<<"请输入要链接的两个节点:"<<endl;
while(1)
{
cin>>nodeOne;
cin>>nodeTwo;
if(nodeOne==-1&&nodeTwo==-1)
return;
//调整节点的位置哦
edgeNode *newEdgeN1=new edgeNode();
newEdgeN1->sequence=nodeTwo;
newEdgeN1->next=graphl[nodeOne].next;
graphl[nodeOne].next=newEdgeN1;
edgeNode* newEdgeN2=new edgeNode();
newEdgeN2->sequence=nodeOne;
newEdgeN2->next=graphl[nodeTwo].next;
graphl[nodeTwo].next=newEdgeN2;
}
}
//释放内存
void deleteMem(DataNode * graphl)
{
edgeNode *p=NULL;
edgeNode *TEMP=NULL;
for(int i=0;i<NUM;++i)
{
p=GraphList[i].next;
while(p)
{
TEMP=p;
p=p->next;
delete TEMP;
}
}
}
//DFS深度优先遍历
void DFStraverse(DataNode * graphl,int v)
{
visited[v]=1;
cout<<"深度遍历节点:"<<graphl[v].savedData<<endl;
edgeNode* p=graphl[v].next;
while(p)
{
if(!visited[p->sequence])
{
DFStraverse(graphl,p->sequence);//remember:递归结束之前不会运行后面的语句。
}
p=p->next;
}
}
void DFS(DataNode * graphl)
{
int i;
for(i=0;i<NUM;++i)
{
visited[NUM]=0;
}
for(i=0;i<NUM;++i)
{
if(!visited[i])
{
DFStraverse(graphl,i);
}
}
}
//BFS广度优先搜索
void BFStraverse(DataNode * graphl )
{
//visited[v]=1;
cout<<"广度优先遍历点:";
edgeNode* EN;
//不能递归实现,可用队列来实现
int j;
for(int i=0;i<NUM;++i)
{
visited[NUM]=0;
}
for(int i=0;i<NUM;++i)
{
if(!visited[i])
{
que_DN.push(i);
visited[i]=1;
cout<<graphl[i].savedData<<",";
while(!que_DN.empty())
{
int v=que_DN.front();
que_DN.pop();
EN=graphl[v].next;
while(EN)
{
j=EN->sequence;
if(!visited[j])
{
que_DN.push(j);
visited[j]=1;
cout<<graphl[j].savedData<<",";
}
EN=EN->next;
}
}
}
}
}
void BFS(DataNode * graphl)
{
int i;
for(i=0;i<NUM;++i)
{
visited[i]=0;
}
BFStraverse(graphl );
}
int main()
{
createGraph(GraphList);
cout<<"输出链表序列:"<<endl;
for(int i=0;i<NUM;++i)
{
edgeNode *p=GraphList[i].next;
cout<<i<<":"<<GraphList[i].savedData<<" ";
while(p)
{
cout<< p->sequence<<",";
p=p->next;
}
cout<<"\n";
}
DFS(GraphList);
BFS(GraphList);
deleteMem(GraphList);
return 0;
}
BFS 的目的是为了,备份之前节点。
测试: