有向图的强连通判断
定理:一个有向图是强连通的,当且仅当G中有一个回路,它至少包含每个节点一次。( 百度百科)
简单说就是从有向图的每个顶点出发都能到达图的其它顶点。
就用这个思想写代码:
#include"bits/stdc++.h"
using namespace std;
#define MAX 10
#define INFINITE 201201//定义无限大
typedef int EdgeType;//定义边类型
typedef char VertexType;//定义顶点类型
typedef struct{
EdgeType edge[MAX][MAX];//邻接矩阵
int numEdges,numVertexs;//边和顶点数量
}MGraph;
void BFS(MGraph *Test,int i,bool visited[]){
queue <int> M;//创建队列
int j;
M.push(i);
while(!M.empty()){
j=M.front();
visited[j]=true;//标记
M.pop();
for(int k=0;k<Test->numVertexs;k++){
if(Test->edge[j][k]==1&&!visited[k]){
M.push(k);//将后一顶点放入队列
visited[k]=true;
}
}
}
}
void Init(MGraph *Test){//初始化
for(int i=0;i<Test->numVertexs;i++){
for(int j=0;j<Test->numVertexs;j++){
if(i==j){
Test->edge[i][j]=0;
}
else{
Test->edge[i][j]=INFINITE;
}
}
}
}
void CreateMatrix(MGraph *Test){//创建矩阵
for(int i=0;i<Test->numEdges;i++){
int x,y;
cin>>x>>y;
Test->edge[x][y]=1;
}
}
int main(){
MGraph Test;
cin>>Test.numVertexs>>Test.numEdges;
Init(&Test);
CreateMatrix(&Test);
for(int i=0;i<Test.numVertexs;i++){//我们从每一个顶点出发进行一次BFS
int flag=0; //标记
bool visited[MAX]={false};//初始化
BFS(&Test,i,visited);
for(int i=0;i<Test.numVertexs;i++){
flag+=visited[i];
}
if(flag!=Test.numVertexs){//若flag的值和边的数量不等则说明有顶点没到达
cout<<"no";//直接输出结果,结束程序
return 0;
}
}
cout<<"yes";
return 0;
}
有不足请指教