深度优先遍历最主要的思想是利用了 栈的概念。
利用栈来存储已经遍历过的节点。
#include <stdio.h>
#include <stdlib.h>
#define VertexNum 9
struct DFS_Node
{
int v;
struct DFS_Node *next;
};
typedef struct DFS_Node *Graph;
struct DFS_Node DFS_Head[VertexNum];
int g_visited[VertexNum];
void dfs_create_graph(int v1, int v2)
{
Graph pointer;
Graph New = (Graph)malloc(sizeof(struct DFS_Node));
if (New != NULL)
{
New->v = v2; /*临近节点*/
New->next = NULL;
pointer = &(DFS_Head[v1]);
while(pointer->next !=NULL)
pointer = pointer->next;
pointer->next = New;
}
}
void dfs_print_graph(struct DFS_Node *DFS_Head)
{
Graph pointer;
pointer = DFS_Head->next;
while (pointer!=NULL)
{
printf("[%d]", pointer->v);
pointer = pointer->next;
}
printf("\n");
}
void DFS(int v)
{
Graph pointer;
g_visited[v] = 1; /*已经查找过了*/
printf("[%d]==>", v);
pointer = DFS_Head[v].next;
while(pointer != NULL)
{
if (g_visited[pointer->v] == 0)
DFS(pointer->v);
pointer = pointer->next;
}
}
int main(int argc, char **argv)
{
int i = 0;
int DFS_Node[20][2] = {
{1,2}, {2,1}, {1,3}, {3,1},
{2,4}, {4,2}, {2,5}, {5,2},
{3,6}, {6,3}, {3,7}, {7,3},
{4,8}, {8,4}, {5,8}, {8,5},
{6,8}, {8,6}, {7,8}, {8,7}
};
for (i = 0; i < VertexNum; i++)
{
DFS_Head[i].v = i;
DFS_Head[i].next = NULL;
g_visited[i] = 0;
}
for(i = 0; i < 20; i++)
{
dfs_create_graph(DFS_Node[i][0], DFS_Node[i][1]);
}
printf("++ Graph ++\n");
for (i = 0; i< VertexNum; i++)
{
printf("Ver[%d] : ", i);
dfs_print_graph(&DFS_Head[i]);
}
printf("Depth-First-Search : \n");
printf("[Begin]==>");
DFS(1);
printf("[End]");
return 0;
}