In graph theory, an Eulerian Path is a path in a graph that visits every edge exactly once. An Eulerian Cycle, also known as an Euler circuit or Euler tour, is an Eulerian path that starts and ends at the same vertex. These concepts are named after Leonhard Euler, who first discussed them in his 1736 paper on the Seven Bridges of Königsberg problem.
Understanding Eulerian cycles and paths is crucial for various applications, including network design, routing problems, and even puzzles like mazes. In this tutorial, we will explore the definitions, properties, algorithms to detect them, and real-world applications of Eulerian cycles and paths.
Fleury's algorithm is a method to find an Eulerian path in a graph. It was one of the first algorithms proposed for this problem and is based on the following steps:
Here's a Python implementation of Fleury's algorithm:
def fleurys_algorithm(graph):
def dfs(u, path):
for v in range(len(graph)):
if graph[u][v] == 1:
graph[u][v] = 0
graph[v][u] = 0
dfs(v, path)
path.append(u)
# Find a vertex with an odd degree to start the Eulerian Path
start_vertex = None
for i in range(len(graph)):
if sum(graph[i]) % 2 != 0:
start_vertex = i
break
if start_vertex is None:
start_vertex = 0
path = []
dfs(start_vertex, path)
return path[::-1]
# Example usage
graph = [
[0, 1, 0, 0],
[1, 0, 1, 1],
[0, 1, 0, 1],
[0, 1, 1, 0]
]
eulerian_path = fleurys_algorithm(graph)
print("Eulerian Path:", eulerian_path)
Hierholzer's algorithm is a more efficient method to find an Eulerian cycle. It uses depth-first search (DFS) and runs in O(E + V) time, where E is the number of edges and V is the number of vertices.
Here's a Python implementation of Hierholzer's algorithm:
def hierholzers_algorithm(graph):
def dfs(u, path):
while graph[u]:
v = graph[u].pop()
dfs(v, path)
path.append(u)
# Find an Eulerian Cycle starting from any vertex
start_vertex = 0
path = []
dfs(start_vertex, path)
return path[::-1]
# Example usage
graph = {
0: [1],
1: [2, 3],
2: [1, 3],
3: [1, 2]
}
eulerian_cycle = hierholzers_algorithm(graph)
print("Eulerian Cycle:", eulerian_cycle)
Eulerian cycles and paths are fundamental concepts in graph theory with wide-ranging applications. Understanding how to detect and utilize these structures can lead to more efficient solutions for various problems in computer science and beyond. By mastering the algorithms discussed here, you'll be well-equipped to tackle complex network design and routing challenges.