先说思路:
DFS两种方法实现:递归和非递归。【不难,看下面代码即可】。
试实现邻接矩阵存储图的深度优先遍历。
函数接口定义:
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) );
其中MGraph是邻接矩阵存储的图,定义如下:
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv; /* 顶点数 */
int Ne; /* 边数 */
WeightType G[MaxVertexNum][MaxVertexNum]; /* 邻接矩阵 */
};
typedef PtrToGNode MGraph; /* 以邻接矩阵存储的图类型 */
函数DFS应从第V个顶点出发递归地深度优先遍历图Graph,遍历时用裁判定义的函数Visit访问每个顶点。当访问邻接点时,要求按序号递增的顺序。题目保证V是图中的合法顶点。
裁判测试程序样例:
#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;
}
/* 你的代码将被嵌在这里 */
输入样例:给定图如下
5
输出样例:
DFS from 5: 5 1 3 0 2 4 6
/*递归
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) )//void (*Visit)(Vertex)是把函数作为参数,可以不用管
{
int i;
Visit(V);
Visited[V]=true;//注意:改标记!!!
for(i=0;i<Graph->Nv;i++){
if(Graph->G[V][i]<INFINITY && Visited[i]==false){//注意:直接相连(权值小于无穷)&& 没有被访问过,两者需要同时成立
DFS(Graph,i,Visit);
}
}
}*/
/*非递归------为了降重我选这个自己写的非递归的,递归的太常用,嘿嘿*/
void DFS( MGraph Graph, Vertex V, void (*Visit)(Vertex) )
{
int i;
Vertex stack[MaxVertexNum];int top=-1;//定义栈
Vertex p;
Visit(V);
Visited[V]=true;
stack[++top]=V;
while(top!=-1){
for(i=0;i<Graph->Nv;i++){
if(Graph->G[V][i]<INFINITY && Visited[i]==false){
Visit(i);
Visited[i]=true;
stack[++top]=i;
V=stack[top];
break;//深度查找 :找到一个,就结束当前循环;然后以找到的i为V进行下一次循环
}
}
if(i==Graph->Nv){
V=stack[--top];//注意:出栈的条件:找了一圈都没有找到符合输出的,就出栈--后退
}
}
}