背景(background):
考虑下图三个图形,要求不重复地走完所有路径。其中,若能回到起点,则这样的环路称为欧拉回路(Euler Circuit),若能不重复走完路径,但终点不一定是起点,则这样的环游称为欧拉环游(Euler tour)。两种问题统称为欧拉路径问题(Euler Path Problem)。
两种欧拉路径问题随然稍有不同,但解法思路一致,以欧拉回路问题介绍Fleury算法。在介绍之前引入欧拉回路的一般性质。
欧拉回路的一般性质:
1、当终点必须终止在起点的欧拉回路当图是连通的并且每个顶点的度(即边的个数)是偶数时才有可能存在。因为在欧拉回路中满足有入必有出。如果任一顶点的度为奇数,则通过该边只能进而无法出(上图右图所示)。如果如果恰有两个顶点的度数为奇数,则在一个奇数度的顶点出发在另一个奇数度的顶点结束,欧拉回路依然可能存在(上图左所示)。如果奇数的顶点数多于两个,则欧拉回路也不存在。
2、事实上,通过条件1可以得到欧拉回路的充分必要条件。即:所有顶点的度均为偶数的连通图必有欧拉回路。
Fleury算法语言描述:
设为无向图,求的一条欧拉回路的方法为:
1)取的起点,令;
2)设到依次经过顶点,按如下方法选取下一顶点:
1:与关联;
2:除非无别的边可选择,否则到的边不能是剩余顶点的桥(去除该边则整个图不连通);
3)当2)步骤完成时算法结束,生成一条欧拉路径。
Fleury算法行为描述:
1,选择为起点。进行深度优先遍历(最大顶点优先遍历)并标记已经经过的边,直到再次出现重复顶点(v1 -> v8 ->v9 ->v6 -> v7 -> v8),以v8为起点进行深度优先遍历(此时不包括已经遍历的边,即已经遍历过的边不存在了),依次经过v8 -> v2 -> v9 -> v4(v6已经遍历过将不存在了) -> v6 -> v5 -> v4 回到v4,以v4为起点进行深度优先遍历,依次经过v4 -> v3 -> v2 -> v1回到起始地点。整个流图如下所示:
Fleury算法编程实现:
//main.cpp
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
const int N = 20;
//define the Stack container
struct Stack{
int top;
int vertex[N];
}s;
int graph[N][N];
//dfs algorithm to traverse connection path
void dfs(int start, int numVertex);
//fleury algorithm to output the Eular loop
void fleury(int start, int numVertex);
int main(){
int numVertex, numEdge;
int u, v, degree;
int start, num, i;
ifstream fin("input.txt");
fin >> numVertex >> numEdge;
memset(graph, 0, sizeof(graph));
//update the graph by file input
for(i = 0; i < numEdge; i++){
fin >> u >> v;
graph[u-1][v-1] = graph[v-1][u-1] = 1;
}
//claculate the degree of vertex
for(i = 0; i < numVertex; i++){
degree = 0;
for(int j = 0; j < numVertex; j++){
degree += graph[i][j];
}
//odd number degree case
if(degree & 1){
start = i;
num++;
}
}
//only the degree of vertex is even, than there will exist the Eular loop
if(num == 0 || num == 2){
fleury(start, numVertex);
}else{
cout << "The graph has no Eular Loop !" << endl;
}
cout << " done ." << endl;
return 0;
}
void dfs(int start, int numVertex){
//push the start vertex into stack;
s.vertex[++s.top] = start;
for(int i = 0; i < numVertex; i++){
//update the visited vertex
if(graph[i][start] > 0){
graph[i][start] = graph[start][i] = 0;
//iterative call the dfs algorithm to find the connection path
dfs(i, numVertex);
break;
}
}
}
void fleury(int start, int numVertex){
s.top = 0;
s.vertex[s.top] = start;
bool flag;
while(s.top >= 0){
flag = false;
//find the connection vertex and set flag
for(int i = 0; i < numVertex; i++){
if(graph[s.vertex[s.top]][i] > 0){
flag = true;
break;
}
}
//the vertex has only one connection vertex
if(!flag){
cout << (s.vertex[s.top--] + 1) << " -> ";
//the vertex has more than one connection vertex
}else{
dfs(s.vertex[s.top--], numVertex);
}
}
}
//input.txt
9 14
1 2
1 8
2 3
2 8
2 9
3 4
4 5
4 6
4 9
5 6
6 7
6 9
7 8
8 9
practice makes perfect !