欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个无向图,问是否存在欧拉回路?
输入格式:
输入第一行给出两个正整数,分别是节点数N (1≤N≤1000)和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。
输出格式:
若欧拉回路存在则输出1,否则输出0。
输入样例1:
6 10
1 2
2 3
3 1
4 5
5 6
6 4
1 4
1 6
3 4
3 6
输出样例1:
1
输入样例2:
5 8
1 2
1 3
2 3
2 4
2 5
5 3
5 4
3 4
输出样例2:
0
解题过程:
欧拉回路要求:
(1)所有顶点度为偶数;//邻接矩阵很适合统计度
(2)图连通。(可用并查集)
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 1000
typedef int Vertex;
typedef struct MGNode *MGraph;
struct MGNode{
int Nv;
int Ne;
int G[MaxVertexNum][MaxVertexNum];
};
typedef struct ENode *Edge;
struct ENode{
Vertex V1,V2;
};
MGraph CreateGraph(int N){
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct MGNode));
Graph->Nv = N;
Graph->Ne = 0;
Vertex V,W;
for(V=0; V<Graph->Nv;V++){
for(W=0; W<Graph->Nv; W++){
Graph->G[V][W] = 0;
}
}
return Graph;
}
void InsertEdge(MGraph Graph, Edge E){
/**插入无向边**/
Graph->G[E->V1-1][E->V2-1] = 1;
Graph->G[E->V2-1][E->V1-1] = 1;
}
MGraph BuildGraph(){
int N;
scanf("%d",&N);
MGraph Graph;
Graph = CreateGraph(N);
scanf("%d",&(Graph->Ne));
if(Graph->Ne){
Edge E = (Edge)malloc(sizeof(struct ENode));
int i;
for(i=0;i<Graph->Ne;i++){
scanf("%d %d",&E->V1,&E->V2);
InsertEdge(Graph, E);
}
}
return Graph;
}
int CheckDegree(MGraph Graph){
int Degree[MaxVertexNum];
int i,j;
for(i=0;i<Graph->Nv;i++){
Degree[i] = 0;
}
int flag = 0;/**标志位 0-度为偶数,1-度为奇数**/
for(i=0;i<Graph->Nv;i++){
for(j=0;j<Graph->Nv;j++){
Degree[i] += Graph->G[i][j];//由于是无向边 ,对称,只需考虑行
}
//printf("i:%d %d
",i,Degree[i]);
/**判断是否为偶数边**/
if(Degree[i]%2!=0){
flag = 1;
break;
}
}
if(flag) return 0;
else
return 1;
}
int Visited[MaxVertexNum];
int DST(MGraph Graph, Vertex V, int cnt){
Visited[V] = 1;
//printf("1
");
if(cnt == Graph->Nv){
/*若cnt等于顶点数,图连通*/
return 1;
}
else{
Vertex W;
int flag;
for(W=0;W<Graph->Nv; W++){
if(!Visited[W]&&Graph->G[V][W]>0){
cnt++;
flag = DST(Graph, W, cnt);
/*已确定图已连通,快速跳出*/
//printf("%d
",flag);
if(flag){
break;
}
}
}
return flag;
}
}
int GraphCycle(MGraph Graph){
Vertex V,W;
int flag=0;
for(V=0;V<Graph->Nv;V++){
for(W=0;W<Graph->Nv;W++){
Visited[W]=0;
}
if(DST(Graph,V, 1)){
flag = 1;
break;
}
}
if(flag)
return 1;
else
return 0;
}
int main()
{
MGraph Graph;
Graph = BuildGraph();
if(CheckDegree(Graph)&&GraphCycle(Graph)){
printf("1");
}
else
printf("0");
return 0;
}