有向图中的欧拉回路
欧拉路径是一条路径,我们可以通过它精确地访问每条边一次。我们可以多次使用相同的顶点。欧拉回路是一种特殊的欧拉路径。当欧拉路径的起始顶点也与该路径的结束顶点相连时,则称为欧拉回路。
要检查图是否为欧拉图,我们必须检查两个条件:
- 图必须是连通的。
- 每个顶点的入度和出度必须相同。
输入和输出
Input: Adjacency matrix of the graph. 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 0 0 Output: Euler Circuit Found.
算法
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
isEulerCircuit(Graph)
输入:给定的图。
输出:找到一个欧拉回路时返回 True。
Begin if isConnected() is false, then return false define list for inward and outward edge count for each node for all vertex i in the graph, do sum := 0 for all vertex j which are connected with i, do inward edges for vertex i increased increase sum done number of outward of vertex i is sum done if inward list and outward list are same, then return true otherwise return false End
示例
#include<iostream> #include<vector> #define NODE 5 using namespace std; int graph[NODE][NODE] = { {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}, {1, 0, 0, 0, 0}, {0, 0, 1, 0, 0} }; 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; } bool isEulerCircuit() { if(isConnected() == false) { //when graph is not connected return false; } vector<int> inward(NODE, 0), outward(NODE, 0); for(int i = 0; i<NODE; i++) { int sum = 0; for(int j = 0; j<NODE; j++) { if(graph[i][j]) { inward[j]++; //increase inward edge for destination vertex sum++; //how many outward edge } } outward[i] = sum; } if(inward == outward) //when number inward edges and outward edges for each node is same return true; return false; } int main() { if(isEulerCircuit()) cout << "Euler Circuit Found."; else cout << "There is no Euler Circuit."; }
输出
Euler Circuit Found.
广告