欧拉回路:
描述:如果一个图中,存在一条回路,不重复的经过所有的边,我们称其为欧拉回路。
欧拉回路的要求:
无向图:图中没有孤立的点且图中的点的度数均不为奇数。
有向图:图中没有孤立的点且图中点的出度等于入度。
也就是说,只要图中存在欧拉回路,那么从任何点出发,都可以经过一条欧拉回路回到本身。
找欧拉回路:
根据DFS(边)的性质,回溯是记录,可以求出欧拉回路。
有向图与无向图的区别就是在DFS时,要标记的边,有向图标记一条就足以,而无向图需要将两条都标记。
找欧拉通路原理与回路相同,代码也相同。
代码:
输入:
N 点数;m 边数。
接下啦m行,表示边的起点与终点。
输出:
欧拉回路。
View Code
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 #define maxver 1000000 5 #define maxpoint 1000000 6 int first[maxpoint]; 7 int next[maxver]; 8 int v[maxver]; 9 int d[maxpoint]; 10 int vis[maxpoint]; 11 int times; 12 int n,m; 13 void DFS(int start){ 14 for(int k=first[start];k!=-1;k=next[k]){ 15 if(vis[k]==0){ 16 vis[k]=1; 17 /* if(k>m) 18 vis[k-m]=1; 19 else 20 vis[k+m]=1; */ //if is the undirtected graph, use it 21 DFS(v[k]); 22 int temp1=k%m; 23 if(k%m==0) 24 temp1=m; 25 d[times++]=temp1; 26 // d[times++]=start; //if it want to the points' sequence ,use these; 27 } 28 } 29 } 30 int main(){ 31 while(cin>>n>>m){ //cin the number of point and ver 32 memset(first,-1,sizeof(first)); 33 memset(next,-1,sizeof(next)); 34 memset(vis,0,sizeof(vis)); 35 times=1; 36 d[0]=-1; 37 for(int i=1;i<=m;i++){ 38 int temp1,temp2; 39 cin>>temp1>>temp2; //cin the ver's points ()无向图 40 if(first[temp1]==-1){ 41 first[temp1]=i; 42 } 43 else{ 44 int temp3=first[temp1]; 45 first[temp1]=i; 46 next[i]=temp3; 47 } 48 v[i]=temp2; 49 /* if(first[temp2]==-1){ 50 first[temp2]=i+m; 51 } 52 else{ 53 int temp4=first[temp2]; 54 first[temp2]=i+m; 55 next[i+m]=temp4; 56 } 57 v[i+m]=temp1; */ //if is the undircted graph, use it 58 } 59 DFS(1); //the oula return way's start and end point 60 for(int g=1;g<times;g++){ //cout the ver of a oula return way 61 cout<<d[g]<<" "; 62 } 63 cout<<endl; 64 } 65 return 0; 66 }