Given an adjacency matrix representation of an undirected graph. Find if there is any Eulerian Path in the graph. If there is no path print “No Solution”. If there is any path print the path.
Input : [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 0, 0]] Output : 5 -> 1 -> 2 -> 4 -> 3 -> 2 Input : [[0, 1, 0, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [1, 1, 1, 0, 0], [1, 0, 1, 0, 0]] Output : "No Solution"
The base case of this problem is if number of vertices with odd number of edges(i.e. odd degree) is greater than 2 then there is no Eulerian path.
If it has solution and all the nodes has even number of edges then we can start our path from any of the nodes.
If it has solution and exactly two vertices has odd number of edges then we has to start our path from one of these two vertices.
There will not be the case where exactly one vertex has odd number of edges, as there is even number of edges in total.
Process to Find the Path:
- First take an empty stack and an empty path.
- If all the vertices has even number of edges then start from any of them. If two of the vertices has odd number of edges then start from one of them. Set variable current to this starting vertex.
- If the current vertex has at least one adjacent node then first discover that node and then discover the current node by backtracking. To do so add the current node to stack, remove the edge between current node and neighbour node, set current to neighbour node.
- If current node has not any neighbour then add it to path and pop stack set current to popped vertex.
- Repeat process 3 and 4 until the stack is empty and current node has not any neighbour.
After the process path variable holds the Eulerian path.
4 -> 0 -> 1 -> 3 -> 2 -> 1 No Solution 4 -> 3 -> 2 -> 1 -> 4 -> 0 -> 1 -> 3
The runtime complexity of this algorithm is O(E). This algorithm can also be used to find the Eulerian circuit. If the first and last vertex of the path is same then it will be an Eulerian circuit.