妙趣橫生的算法實例1-7

下面是源代碼:

#include <stdio.h>
#include <malloc.h>

int visited[5] = {0, 0, 0, 0, 0};

typedef struct ArcNode
{
	int adjVex;
	struct ArcNode *next;
}ArcNode;

typedef struct VNode
{
	int data;
	ArcNode *firstArc;
}VNode;

void CreateGraph(int n, VNode G[])
{
	int i, e;
	ArcNode *p, *q;
	printf("請輸入各個頂點數據:\n");
	for(i = 0; i < n; i++)
	{
		scanf("%d", &G[i]);
		G[i].firstArc = NULL;
	}

	for(i = 0; i < n; i++)
	{
		printf("輸入與第%d個頂點有連接的頂點在頂點數組中的位置\n", i);
		scanf("%d", &e);
		while (e != -1)
		{
			p = (ArcNode *)malloc(sizeof(ArcNode));
			p->adjVex = e;
			p->next = NULL;
			if(G[i].firstArc == NULL)
			{
				G[i].firstArc = p;
			}else
			{
				q->next = p;
			}

			q = p;
			scanf("%d", &e);
		}
	}
}

int FirstAdj(VNode G[], int v)
{
	if(G[v].firstArc != NULL)
	{
		return G[v].firstArc->adjVex;
	}else
	{
		return -1;
	}
}

int NextAdj(VNode G[], int v)
{
	ArcNode *p = G[v].firstArc->next;
	while(p != NULL)
	{
		if(visited[p->adjVex] == 0)
		{
			return p->adjVex;
		}else
		{
			p = p->next;
		}
	}

	return -1;
	
}

void DFS(VNode G[], int v)
{
	int w;
	printf("%d ", G[v]);
	visited[v] = 1;
	w = FirstAdj(G, v);
	while(w != -1)
	{
		if(visited[w] == 0)
		{
			DFS(G, w);
		}

		w = NextAdj(G, v);
	}
}

void main()
{
	int i = 0;
	VNode G[5];
	CreateGraph(5, G);
	printf("深度遍歷圖的元素爲:\n");
	DFS(G, i);
}


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