无向图求连通部件,和节点访问时刻和离开时刻



#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <queue>
using namespace std; 
char ch[12];
bool gmap[12][12];
bool flag[12];
queue<char> myqueue;
struct Time {
	int s;
	int e;
}mytime[12];
int cnt = 1;
void dfs(int k) {
	mytime[k].s = cnt++;   
	for(int j = 0; j < 12; j++) {
		if((gmap[k][j] == 1)&&(!flag[j])) {
			myqueue.push(ch[j]);
			flag[j] = true;
			dfs(j);
		}
		
	}
	mytime[k].e = cnt++;
}

int main() {
	int i;
	memset(gmap, 0 , sizeof(gmap));
	memset(flag, 0 , sizeof(flag));
	memset(mytime, 0 , sizeof(struct Time));
	for(i =0;i<12;i++) {
		ch[i]= 'A' + i;
	}
	gmap[0][1] = gmap[1][0] = 1;
	gmap[0][4] = gmap[4][0] = 1;
	gmap[4][8] = gmap[8][4] = 1;
	gmap[4][9] = gmap[9][4] = 1;
	gmap[8][9] = gmap[9][8] = 1;

	gmap[2][3] = gmap[3][2] = 1;
	gmap[2][6] = gmap[6][2] = 1;
	gmap[2][7] = gmap[7][2] = 1;
	gmap[3][7] = gmap[7][3] = 1;
	gmap[6][7] = gmap[7][6] = 1;
	gmap[6][10] = gmap[10][6] = 1;
	gmap[7][10] = gmap[10][7] = 1;
	gmap[7][11] = gmap[11][7] = 1;
	for(i = 0 ;i < 12;i++) {
		if(flag[i] == false) {
			while(!myqueue.empty()){
				myqueue.pop();
			}
			myqueue.push(ch[i]);
			flag[i] = true;
			dfs(i);
			while(!myqueue.empty()) {
				cout<<myqueue.front()<<" ";
				myqueue.pop();
			}
			cout<<endl;
		}
	}
	for(i = 0; i< 12; i++) {
		cout<<ch[i]<<"  "<<mytime[i].s<<" "<<mytime[i].e<<endl;
	}
	cout<<endl;
	system("pause");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值