23.基于 邻接表 dfs 的 求连通分支


#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<stack>
#define OK 0
#define ERROR 1
#define MAXSIZE 1000
using namespace std;
typedef int ElemType;
FILE *fp;
void InitFile()
{
	bool e;
	fopen_s(&fp, "data.txt", "r");
	if (!fp) exit(ERROR);
	return;
}
typedef bool Status;


基于 邻接表 dfs 的 求连通分支 

/******
file input:
5
1 2
2 3
4 5
0 0
*******/



typedef struct node
{
	int vertex;
	struct node *link;

}Node, *node_ptr;
int ver_num;
node_ptr vertex;


Status InitGraph()
{
	int a, b, n;//n个节点   对应  1.......n
	fscanf_s(fp, "%d", &n);
	ver_num = n;
	vertex = (node_ptr)malloc(sizeof(Node)*(n + 1));
	if (!vertex) exit(ERROR);
	for (int i = 0; i <= n; i++){ vertex[i].vertex = i; vertex[i].link = NULL; }
	while (fscanf_s(fp, "%d %d", &a, &b) && a && b)
	{
		if (a<1 || a>n || b<1 || b>n)  exit(ERROR);
		node_ptr  c;
		if (!(c = (node_ptr)malloc(sizeof(Node)))) exit(ERROR);
		c->vertex = b;
		c->link = vertex[a].link;
		vertex[a].link = c;

		if (!(c = (node_ptr)malloc(sizeof(Node)))) exit(ERROR);
		c->vertex = a;
		c->link = vertex[b].link;
		vertex[b].link = c;
	}
	return OK;
}

void Output_node(node_ptr t)
{
	printf("----> %d ", t->vertex);
	if (!t->link) putchar(10);
}
void OutputGraph()
{
	printf("节点个数为%d :从 1 到 %d\n", ver_num, ver_num);
	printf("邻接表表示如下:\n");
	int n = ver_num;
	for (int i = 1; i <= n; i++)
	{
		printf("node : %d :  ", i);
		node_ptr t = vertex[i].link;
		while (t)
		{
			Output_node(t);
			t = t->link;
		}
	}
}
int visit[MAXSIZE];
void dfs(int i)
{
	if (!visit[i])
	{
		printf("---->  %d  ", i);
		visit[i] = 1;
		node_ptr t = vertex[i].link;
		while (t)
		{
			dfs(t->vertex);
			t = t->link;
		}
	}
}
queue<node_ptr> Q;

void bfs(int i)
{
	node_ptr t;
	Q.push(vertex + i);
	visit[(vertex + i)->vertex] = 1;
	while (!Q.empty())
	{
		t = Q.front(); Q.pop();
		printf("---->  %d  ", t->vertex);
		//visit[t->vertex] = 1;
		t = t->link;
		while (t)
		{
			if (!visit[t->vertex]) {
				Q.push(vertex + t->vertex);
				visit[(vertex + t->vertex)->vertex] = 1;
			}
			t = t->link;
		}
	}
}

int Connet()
{
	int s = 0;
	for (int i = 1; i <= ver_num; i++)
	{
		if (!visit[i])
		{
			dfs(i);
			printf("\n");
			s++;
		}

	}
	return s;
}

//by zhaoyang @ 2014.4.20

int main()
{
	InitFile();

	InitGraph();
	OutputGraph();

	memset(visit, 0, sizeof(visit));
	printf("\n------------------------正在计算连通分支中:-----------------------\n");
	printf("连通分支数量为 : %d \n", Connet());

	fclose(fp);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值