C++程式:檢查無向圖是否包含尤拉路徑
尤拉路徑是一條路徑,我們可以精確地訪問每個節點一次。我們可以多次使用相同的邊。歐拉回路是尤拉路徑的一種特殊型別。當尤拉路徑的起始頂點也與該路徑的結束頂點連線時。
要檢測尤拉路徑,我們必須遵循以下條件:
- 該圖必須是連通的。
- 現在,當無向圖的任何頂點都沒有奇數度時,它就是一個歐拉回路,它也是一條尤拉路徑。
- 當恰好有兩個頂點具有奇數度時,它是一條尤拉路徑。
輸入

輸出
這兩個圖都有尤拉路徑。
演算法
traverse(u, visited)
輸入:起始節點u和已訪問節點,用於標記已訪問的節點。
輸出:遍歷所有連線的頂點。
Begin mark u as visited for all vertex v, if it is adjacent with u, do if v is not visited, then traverse(v, visited) done End
isConnected(graph)
輸入:圖。
輸出:如果圖是連通的,則返回True。
Begin define visited array for all vertices u in the graph, do make all nodes unvisited traverse(u, visited) if any unvisited node is still remaining, then return false done return true End
isEulerian(Graph)
輸入:給定的圖。
輸出:當存在歐拉回路或路徑時返回1,當不存在尤拉路徑時返回0。
Begin if isConnected() is false, then return false define list of degree for each node oddDegree := 0 for all vertex i in the graph, do for all vertex j which are connected with i, do increase degree done if degree of vertex i is odd, then increase oddDegree done if oddDegree > 0, then return 0 else return 1 End
示例程式碼
#include<iostream>
#include<vector>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{0, 0, 0, 1, 0}};
/*int graph[NODE][NODE] = {{0, 1, 1, 1, 1},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{1, 0, 0, 1, 0}};*/ //uncomment to check Euler Circuit as well as path
/*int graph[NODE][NODE] = {{0, 1, 1, 1, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 0, 0},
{1, 1, 0, 0, 1},
{0, 0, 0, 1, 0}};*/ //Uncomment to check Non Eulerian Graph
void traverse(int u, bool visited[]) {
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) {
if(!visited[v])
traverse(v, visited);
}
}
}
bool isConnected() {
bool *vis = new bool[NODE];
//for all vertex u as start point, check whether all nodes are visible or not
for(int u; u < NODE; u++) {
for(int i = 0; i<NODE; i++)
vis[i] = false; //initialize as no node is visited
traverse(u, vis);
for(int i = 0; i<NODE; i++){
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
}
return true;
}
int isEulerian() {
if(isConnected() == false) //when graph is not connected
return 0;
vector<int> degree(NODE, 0);
int oddDegree = 0;
for(int i = 0; i<NODE; i++) {
for(int j = 0; j<NODE; j++) {
if(graph[i][j])
degree[i]++; //increase degree, when connected edge found
}
if(degree[i] % 2 != 0) //when degree of vertices are odd
oddDegree++; //count odd degree vertices
}
if(oddDegree > 2) //when vertices with odd degree greater than 2
return 0;
return 1; //when oddDegree is 0, it is Euler circuit, and when 2, it is Euler path
}
int main() {
if(isEulerian() != 0) {
cout << "The graph has Eulerian path." << endl;
} else {
cout << "The graph has No Eulerian path." << endl;
}
}輸出
The graph has Eulerian path.
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP