先建立边节点、头节点、图的结构体,深度优先搜索就是先访问起始节点的第一个邻接点,然后访问第一个邻接点的第一个邻接点,类似于树的先序遍历,使用递归算法,广度优先索搜就是依次访问完起始节点的每一个邻接点,然后再依次访问完第一个邻接点的所有邻接点,类似于树的层遍历,需要利用队列进行辅助。在写深度优先遍历时需要写一个找节点在图中序号的函数,只需要遍历图即可。然后输出深度优先和广度优先的遍历结果。具体见代码注释。
以这个图为例
输入示例:
8 9
1 2 3 4 5 6 7 8
1 2
1 6
2 3
2 4
6 7
6 8
3 5
4 5
7 8
代码实现:
#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
const int max_n=100;
bool visited[max_n];//标记数组
queue<int>q;
typedef struct ArcNode{ //边节点
int adjvex; //存放序号
struct ArcNode *nextarc; //指向下一个节点的指针
}ArcNode;
typedef struct VNode{//头节点
int data; //数据值
ArcNode *firstarc; //指向相邻边的指针
}AdjList[max_n];
typedef struct{
AdjList vertices;
int vexnum,arcnum;//图
}ALGraph;
int LocateVex(ALGraph G,int v){ //找到节点在图中存的下表并返回
for(int i=0;i<G.vexnum;++i){
if(G.vertices[i].data==v)
return i;
}
}
void CreatDgraph(ALGraph &G){//创建图
ArcNode *p1;
ArcNode *p2;
cin>>G.vexnum>>G.arcnum;//输入点的个数和边的个数
for(int i=0;i<G.vexnum;++i){
cin>>G.vertices[i].data;//输入数据值
G.vertices[i].firstarc=NULL;//初始化为NULL
}
int v1,v2;
for(int k=0;k<G.arcnum;++k){
cin>>v1>>v2; //输入边的相邻两个点
int i,j;
i=LocateVex(G,v1);//找到两个点的下标
j=LocateVex(G,v2);
p1=new ArcNode;
p2=new ArcNode;//新建边节点
p1->adjvex=j;
p1->nextarc=G.vertices[i].firstarc;
G.vertices[i].firstarc=p1;
p2->adjvex=i;//以头插法插入相邻点及边的信息
p2->nextarc=G.vertices[i].firstarc;
G.vertices[i].firstarc=p2;
}
}
void DFS_AL(ALGraph G,int v){//深度优先搜索
cout<<G.vertices[v].data;
visited[v]=true;
ArcNode *p;
p=G.vertices[v].firstarc;
while(p!=NULL){ //遍历节点的所有相邻点
int w=p->adjvex;
if(!visited[w])
DFS_AL(G,w);//递归遍历
p=p->nextarc;
}
}
void BFS_AL(ALGraph G,int v){//广度优先搜索
cout<<G.vertices[v].data; //输出点的值
visited[v]=true;//并将其标记为true
q.push(v); //入队
while(!q.empty()){
int u=q.front();//取对头元素
q.pop();//并将其出队
ArcNode *p;
p=G.vertices[u].firstarc;
while(p!=NULL){ //遍历其所有的相邻节点
if(!visited[p->adjvex]){
cout<<G.vertices[p->adjvex].data;//输出节点的值
visited[p->adjvex]=true;//并标记
q.push(p->adjvex);//入队
}
p=p->nextarc;
}
}
}
int main()
{
ALGraph G;
CreatDgraph(G);
printf("深度优先搜索;\n");
DFS_AL(G,0);
for(int i=0;i<max_n;i++)
visited[i]=false;
printf("\n广度优先搜索:\n");
BFS_AL(G,0);
return 0;
}