图的广度优先遍历(c语言实现)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

#include 
#include 
#include 
#define N 5
#define BACKSPACE() \
{putchar(8); putchar(32); putchar(10);}

int next_adj(int matrix[][N],int v,int u)
{
	int i;
	if(NULL == matrix)
		return ;
	for(i = u + 1; i < N; i ++)
		if(matrix[v][i])
			return i;
	return -1;
}

int first_adj(int matrix[][N],int v)
{
	int i;
	if (NULL == matrix )
		return -1;
	for(i = 0; i < N; i ++)
		if(matrix[v][i])
			return i;
	return -1;
}

void DFS(int matrix[][N],int v,int visited[])
{
	int u;
	if(visited[v])
		return ;
	printf(" V%d,",v);
	visited[v] = 1;
	u = first_adj(matrix,v);
	while(u >= 0)
	{
		DFS(matrix,u,visited);
		u = next_adj(matrix,v,u);
	}
	return ;
}

int main()
{
	int matrix[N][N] = {0};
	int visited[N] = {0};
	int v1 = -1,
		v2 = -1;
	while(1)
	{
		while(2 != scanf("%d,%d",&v1,&v2))
			getchar();
		if(v1 < 0 || v1 >= N || v2 < 0 || v1 >= N)
			continue;
		if(v1 == v2)
			break;
		matrix[v1][v2] = matrix[v2][v1] = 1;
	}

	for(v1 = 0; v1 < N; v1 ++)
	{
		printf("V%d: ",v1);
		for(v2 = 0; v2 < N; v2 ++)
			if(matrix[v1][v2])
				printf(" V%d,",v2);
		BACKSPACE();
	}	
	v1 = 0;
	for(v1 = 0; v1 < N; v1++)
		DFS(matrix,v1,visited);
	BACKSPACE();
	return 0;
}

转载于:https://my.oschina.net/u/130360/blog/68223

你可能感兴趣的:(图的广度优先遍历(c语言实现))