函数:
#include <stdio.h>
#include <malloc.h>
#include "graph.h"
int visited[MAXV];
void DFS(ALGraph *G, int v)
{
ArcNode *p;
int w;
visited[v]=1;
printf("%d ", v);
p=G->adjlist[v].firstarc;
while (p!=NULL)
{
w=p->adjvex;
if (visited[w]==0)
DFS(G,w);
p=p->nextarc;
}
}
int main()
{
int i;
ALGraph *G;
int A[5][5]=
{
{0,1,0,1,0},
{1,0,1,0,0},
{0,1,0,1,1},
{1,0,1,0,1},
{0,0,1,1,0}
};
ArrayToList(A[0], 5, G);
for(i=0; i<MAXV; i++) visited[i]=0;
printf(" 由2开始深度遍历:");
DFS(G, 2);
printf("\n");
for(i=0; i<MAXV; i++) visited[i]=0;
printf(" 由0开始深度遍历:");
DFS(G, 0);
printf("\n");
return 0;
}
实现: