邻接矩阵存储图的深度优先遍历(递归)
#include <stdio.h>
typedef enum {false, true} bool;
#define MaxVertexNum 10 /* 最大顶点数设为10 */
#define INFINITY 65535 /* ∞设为双字节无符号整数的最大值65535*/
typedef int Vertex; /* 用顶点下标表示顶点,为整型 */
typedef int WeightType; /* 边的权值设为整型 */
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
bool Visited[MaxVertexNum]; /* 顶点的访问标记 */
MGraph CreateGraph(); /* 创建图并且将Visited初始化为false;裁判实现,细节不表 */
void Visit( Vertex V )
{
printf(" %d", V);
}
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );
int main()
{
MGraph G;
Vertex V;
G = CreateGraph();
scanf("%d", &V);
printf("DFS from %d:", V);
DFS(G, V, Visit);
return 0;
}
/* 你的代码将被嵌在这里 */
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) ){
Visited[V]=true; //将顶点标记为已访问
Visit(V); //打印顶点V;
for(int i=0;i<Graph->Nv;i++){ //从第一个顶点开始循环,直到最后一个顶点
if(Graph->G[V][i]<INFINITY&&!Visited[i]) //找到第一个与顶点V相连且为被访问的顶点i
DFS(Graph,i,Visit); //递归
}
}
邻接表存储图的广度优先遍历(非递归)
#include <stdio.h>
typedef enum {false, true} bool;
#define MaxVertexNum 10 /* 最大顶点数设为10 */
typedef int Vertex; /* 用顶点下标表示顶点,为整型 */
/* 邻接点的定义 */
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV; /* 邻接点下标 */
PtrToAdjVNode Next; /* 指向下一个邻接点的指针 */
};
/* 顶点表头结点的定义 */
typedef struct Vnode{
PtrToAdjVNode FirstEdge; /* 边表头指针 */
} AdjList[MaxVertexNum]; /* AdjList是邻接表类型 */
/* 图结点的定义 */
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
AdjList G; /* 邻接表 */
};
typedef PtrToGNode LGraph; /* 以邻接表方式存储的图类型 */
bool Visited[MaxVertexNum]; /* 顶点的访问标记 */
LGraph CreateGraph(); /* 创建图并且将Visited初始化为false;裁判实现,细节不表 */
void Visit( Vertex V )
{
printf(" %d", V);
}
void BFS ( LGraph Graph, Vertex S, void (*Visit)(Vertex) );
int main()
{
LGraph G;
Vertex S;
G = CreateGraph();
scanf("%d", &S);
printf("BFS from %d:", S);
BFS(G, S, Visit);
return 0;
}
void BFS ( LGraph Graph, Vertex S, void (*Visit)(Vertex) ){
Vertex queue[11]; //int型数组
int l=0,r=0;
Visited[S]=true;
Visit(S);
queue[r++]=S;
PtrToAdjVNode p;
while(l<r){
p=Graph->G[queue[l++]].FirstEdge; //访问结点 对应的 邻接表表头 结点出队
while(p){
Vertex v=p->AdjV; //邻接点下表
if(!Visited[v]){ //判断该结点是否被访问过
Visited[v]=true;
Visit(v); //打印该结点
queue[r++]=v; //入队
}
p=p->Next;
}
}
}