找出图中的所有连通子图(创建图的邻接表,深度优先遍历查找子图)

/* 利用深度优先遍历,找出图中的所有连通图(子图)
 * 图用邻接表表示 *graph[], 利用边的信息来创建adjacency lists
 */
#include<stdio.h>
#include<stdlib.h>

#define MAXVERTICES		20
#define MAXEDGES		20

typedef enum {
		FALSE,
		TRUE,
		TRISTATE
} bool;

typedef struct node
{
	int dst;
	struct node *next;
}node_t;

/* print graph in adjacency lists */
void printGraph(node_t *graph[], int nvert)
{
	int i, j;
	for(i=0; i<nvert; i++)
	{
		node_t *ptr;
		printf("node %d: ", i);
		for(ptr = graph[i]; ptr; ptr=ptr->next)
			printf("[%d]", ptr->dst);
		putchar('\n');
	}
	
}

/*****************************find all connected components****************************************/
/* 头插法创建邻接表(没有单独的头节点,只有一个头指针,即指针数组) */
/* 此处因为头指针会改变,所以要传入指针的指针 */
/* @ptr: adjacency list head (*graph[]) 
 * @dst: 待插入的节点(在graph中index)
 */
void insertEdge(node_t **ptr, int dst)
{
	node_t *newnode = (node_t *)malloc(sizeof(node_t));
	newnode->dst = dst;
	newnode->next = *ptr;
	*ptr = newnode;
}

/* build adjacency lists for graph according to edges */
/* graph[]: adjacency lists head */
void buildGraph(node_t *graph[], int edges[2][MAXEDGES], int nedges)
{
	int i;
	for(i=0; i<nedges; i++)
	{
		insertEdge(graph+edges[0][i], edges[1][i]);
		insertEdge(graph+edges[1][i], edges[0][i]);
	}
}

/* depth-first traverse */
void dfs(int v, int *visited, node_t *graph[] )
{
	node_t *ptr;
	visited[v] = TRISTATE;
	for(ptr=graph[v]; ptr; ptr=ptr->next)
		if(visited[ptr->dst] == FALSE)
				dfs(ptr->dst, visited, graph);
}

void printSetTriState(int *visited, int nvert)
{
	int i;
	for(i=0; i<nvert; i++)
		if(visited[i] == TRISTATE)
		{
			printf("%d ", i);
			visited[i] = TRUE;
		}
	printf("\n\n");
}

/* print all connected components of graph represented using INC lists */
/* @method:  从第一个节点开始深度遍历节点,当仍然有未被访问的节点时,
 * 说明该节点属于另一个图,所以再以该节点为起点,深度遍历,则可找出另一个图
 */
void compINC(node_t *graph[], int nvert)
{
	int *visited;
	int i;
	
	visited = (int *)malloc(nvert * sizeof(int));
	 for(i=0; i<nvert; ++i )
        visited[i] = FALSE;

	for(i=0; i<nvert; i++)
		if(visited[i] == FALSE)
		{
			dfs(i, visited, graph);
			printSetTriState(visited, nvert);
		}
	free(visited);
}

main(void)
{
    /* 根据边的信息来创建adjacency lists */
	int edges[][MAXEDGES] = { {0,2,4,5,5,4 },
								{1,1,3,4,6,6}
							 };
	int nvert = 7;
	int nedges = 6;
	node_t **graph = (node_t **)calloc(nvert, sizeof(node_t *));
	buildGraph(graph, edges, nedges);
	printGraph(graph, nvert);
	printf("All connected components (sub-graphs): \n");
	compINC(graph, nvert);
	return 0;
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/yangjin_unique/article/details/7843432
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞