领接矩阵实现
#include"stdio.h"
#include"stdlib.h"
typedef enum{FALSE,TRUE} Boolean;
#define MaxVertexNum 10
typedef int Vertex;
typedef struct{
int arcs[MaxVertexNum][MaxVertexNum];
int vexnum,arcnum;
}MGraph;
Boolean visited[MaxVertexNum];
void CreatMGraph(MGraph *G);
void DFS(MGraph G,Vertex v);
int main()
{
Vertex v;
MGraph G;
CreatMGraph(&G);
scanf("%d", &v);
printf("DFS from %d:",v);
DFS(G,v);
return 0;
}
具体代码如下:
void DFS(MGraph G,Vertex v)
{
printf(" %d",v);
visited[v]=1;
for(int w=0;w<G.vexnum;w++)
{
if((G.arcs[v][w]!=0)&&(!visited[w]))
DFS(G,w);
}
}
领接表实现:
#include"stdio.h"
#include"stdlib.h"
#define MAX_VERTEX_NUM 10
typedef int Vertex;
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode{
Vertex data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum,arcnum;
} ALGraph;
typedef enum{FALSE,TRUE} Boolean;
Boolean visited[MAX_VERTEX_NUM];
void CreatALGraph(ALGraph *G);
void DFS(ALGraph *G,int v);
int main()
{
Vertex v;
ALGraph G;
CreatALGraph(&G);
scanf("%d", &v);
printf("DFS from %d:",v);
DFS(&G,v);
return 0;
}
具体代码如下:
void DFS(ALGraph *G,int i)
{
ArcNode *pre;
visited[i]=1;
printf(" %d",i);
for(pre=G->vertices[i].firstarc;pre!=NULL;pre=pre->nextarc)
{
if(visited[pre->adjvex]==0)
{
DFS(G,pre->adjvex);
}
}
}