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



#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");
}



你可能感兴趣的:(无向图求连通部件,和节点访问时刻和离开时刻)