數據結構與算法8:圖的深度優先搜索

    圖的深度優先遍歷的基本思想就是沿着一個方向走到底,發現無路可走後退一步接着走,再退一步接着走,直到退回到起點。如果圖是連通的,那麼一定可以遍歷全部節點。這種方式很容易想到遞歸的方式去實現。

    下面是C語言代碼,圖以鄰接表的方式表示。

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

typedef struct ptr
{
	int pos;
	struct ptr* next;
} ptr;

struct node
{
	char data;
	int visited;
	ptr* p;
};

int n;

void createGraph(struct node g[])
{
	int i, j, eNum, pos;
	ptr* p1;
	ptr* p2;
	printf("How many nodes:");
	scanf("%d", &n);
	for (i = 0; i < n; ++i)
	{
		printf("%dth node:", i);
		getchar();
		scanf("%c", &g[i].data);
		g[i].visited = 0;
		g[i].p = NULL;
		printf("  How many edges:");
		scanf("%d", &eNum);

		for (j = 0; j < eNum; ++j)
		{
			printf("%dth edge:", j);
			scanf("%d", &pos);
			p2 = (ptr*)malloc(sizeof(ptr));
			p2->pos = pos;
			p2->next = NULL;
			if (g[i].p != NULL)
			{
				p1->next = p2;
				p1 = p2;
			}
			else
			{
				g[i].p = p2;
				p1 = p2;
			}
		}
	}
}

void dfs(struct node g[], int pos)
{
	ptr* p = NULL;
	if (g[pos].visited == 1)
	{
		return;
	}
	else
	{
		g[pos].visited = 1;
		printf("%c ", g[pos].data);
		p = g[pos].p;
		while (p != NULL)
		{
			dfs(g, p->pos);
			p = p->next;
		}
	}
}

int main()
{
	struct node g[MAX];
	createGraph(g);
	dfs(g, 0);
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章