Skip to content

Commit 76061ab

Browse files
Reshad-Hasanpoyea
authored andcommitted
added eulerian path and circuit finding algorithm (#787)
1 parent c4d1682 commit 76061ab

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Eulerian Path is a path in graph that visits every edge exactly once.
2+
# Eulerian Circuit is an Eulerian Path which starts and ends on the same
3+
# vertex.
4+
# time complexity is O(V+E)
5+
# space complexity is O(VE)
6+
7+
8+
# using dfs for finding eulerian path traversal
9+
def dfs(u, graph, visited_edge, path=[]):
10+
path = path + [u]
11+
for v in graph[u]:
12+
if visited_edge[u][v] == False:
13+
visited_edge[u][v], visited_edge[v][u] = True, True
14+
path = dfs(v, graph, visited_edge, path)
15+
return path
16+
17+
18+
# for checking in graph has euler path or circuit
19+
def check_circuit_or_path(graph, max_node):
20+
odd_degree_nodes = 0
21+
odd_node = -1
22+
for i in range(max_node):
23+
if i not in graph.keys():
24+
continue
25+
if len(graph[i]) % 2 == 1:
26+
odd_degree_nodes += 1
27+
odd_node = i
28+
if odd_degree_nodes == 0:
29+
return 1, odd_node
30+
if odd_degree_nodes == 2:
31+
return 2, odd_node
32+
return 3, odd_node
33+
34+
35+
def check_euler(graph, max_node):
36+
visited_edge = [[False for _ in range(max_node + 1)] for _ in range(max_node + 1)]
37+
check, odd_node = check_circuit_or_path(graph, max_node)
38+
if check == 3:
39+
print("graph is not Eulerian")
40+
print("no path")
41+
return
42+
start_node = 1
43+
if check == 2:
44+
start_node = odd_node
45+
print("graph has a Euler path")
46+
if check == 1:
47+
print("graph has a Euler cycle")
48+
path = dfs(start_node, graph, visited_edge)
49+
print(path)
50+
51+
52+
def main():
53+
G1 = {
54+
1: [2, 3, 4],
55+
2: [1, 3],
56+
3: [1, 2],
57+
4: [1, 5],
58+
5: [4]
59+
}
60+
G2 = {
61+
1: [2, 3, 4, 5],
62+
2: [1, 3],
63+
3: [1, 2],
64+
4: [1, 5],
65+
5: [1, 4]
66+
}
67+
G3 = {
68+
1: [2, 3, 4],
69+
2: [1, 3, 4],
70+
3: [1, 2],
71+
4: [1, 2, 5],
72+
5: [4]
73+
}
74+
G4 = {
75+
1: [2, 3],
76+
2: [1, 3],
77+
3: [1, 2],
78+
}
79+
G5 = {
80+
1: [],
81+
2: []
82+
# all degree is zero
83+
}
84+
max_node = 10
85+
check_euler(G1, max_node)
86+
check_euler(G2, max_node)
87+
check_euler(G3, max_node)
88+
check_euler(G4, max_node)
89+
check_euler(G5, max_node)
90+
91+
92+
if __name__ == "__main__":
93+
main()

0 commit comments

Comments
 (0)