图——邻接矩阵DFS和BFS:图——邻接表的DFS和BFS:
#include<stdio.h>
#define INF 65536
#define max 100
//
邻接矩阵
typedef
struct {
//
int no;
//
编号
int info;
//
权值信息
}vertex;
//
顶点
typedef
struct{
int edge[max][max];
int v_num,e_num;
//
顶点v和边e
//
vertex vexs[max];
//
顶点信息
}graph;
typedef
struct node{
int vetex;
//
顶点
struct node * next;
int info;
//
权值
}node;
typedef
struct vnode{
//
int data;
node *next;
}vnode;
typedef
struct {
vnode list[max];
int n,e;
//
顶点n,边e
}Agraph;
void creatg(graph &g){
int i,j;
int a[max][
6]={
0,
6,
1,
5,
0,
0,
6,
0,
5,
0,
0,
0,
1,
5,
0,
5,
6,
4,
5,
0,
5,
0,
0,
2,
0,
0,
6,
0,
0,
6,
0,
0,
4,
2,
6,
0
};
g.v_num=
6;
g.e_num=
10;
for(i=
0;i<g.v_num;i++)
for(j=
0;j<g.v_num;j++){
if(a[i][j]!=
0)
g.edge[i][j]=a[i][j];
else
g.edge[i][j]=INF;
}
}
void dfs(graph &g,
int v,
int *visit){
int i;
visit[v] =
1;
printf(
“
%2d ->
“,v+
1);
for(i =
0;i <g.v_num;i++)
if(visit[i] ==
0 && g.edge[v][i]!=INF)
dfs(g,i,visit);
}
void bfs(graph g,
int v,
int *visit)
//
邻接矩阵广度遍历;{
int i,Queue[max],rear,front;
visit[v]=
1;
printf(
“
%2d ->
“,v+
1);
rear=front=
0;
rear=(rear+
1)%g.v_num;
Queue[rear]=v;
while(rear!=front){
front=(front+
1)%g.v_num;
for(i=
0;i<g.v_num;i++)
if(visit[i]==
0&&g.edge[Queue[front]][i]!=INF)
{
visit[i] =
1;
printf(
“
%2d ->
“,i+
1);
rear = (rear+
1)%g.v_num;
Queue[rear] = i;
}
}
}
//
将邻接矩阵转换城邻接表
void change(graph g,Agraph *&G){
int i,j,n=g.v_num;
node *p;
G=
new Agraph;
for(i=
0;i<n;i++)
G->list[i].next=NULL;
for(i=
0;i<n;i++)
for(j=n-
1;j>=
0;j–)
if(g.edge[i][j]!=
0){
p=
new node;
p->vetex=j;
p->info=g.edge[i][j]; p->next=G->list[i].next;
G->list[i].next=p;
}
G->n=n;
G->e=g.e_num;
}
void dfs2(Agraph *G,
int v,
int *visit){
node *p;
visit[v]=
1;
printf(
“
%2d ->
“,v+
1);
p=G->list[v].next;
while(p!=NULL){
if(visit[p->vetex]==
0)
dfs2(G,p->vetex,visit);
p=p->next;
}
}
void travel(graph &g,Agraph *G){
int i,visit[max];
//
DFS
printf(
“
邻接矩阵的深度优先搜索遍历\n
“);
for(i=
0;i<max;i++)
visit[i]=
0;
for(i=
0;i<g.v_num;i++)
if(visit[i]==
0)
dfs(g,i,visit);
printf(
“
\n
“);
//
BFS
printf(
“
邻接矩阵的广度优先搜索遍历\n
“);
for(i=
0;i<g.v_num;i++)
visit[i]=
0;
for(i=
0;i<g.v_num;i++)
if(visit[i]==
0)
bfs(g,i,visit);
printf(
“
\n
“);
printf(
“
邻接表的深度优先遍历\n
“);
for(i=
0;i<max;i++)
visit[i]=
0;
dfs2(G,
0,visit);
printf(
“
\n
“);
}
int main()
{
graph g;
creatg(g);
Agraph *G;
change(g,G);
travel(g,G);
prim(g,
0);
}