forked from dimpeshpanwar/Java-Advance-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHierholzerAlgorithm.java
More file actions
77 lines (66 loc) · 1.86 KB
/
HierholzerAlgorithm.java
File metadata and controls
77 lines (66 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Hierholzer's Algorithm
* ----------------------
* Finds Eulerian Circuit or Path in a Graph.
*
* Requirements:
* - For Eulerian Circuit: Every vertex has even degree.
* - For Eulerian Path: Exactly two vertices have odd degree.
*
* Time Complexity: O(E)
*/
import java.util.*;
class HierholzerAlgorithm {
static class Graph {
int V;
List<LinkedList<Integer>> adj;
Graph(int V) {
this.V = V;
adj = new ArrayList<>();
for (int i = 0; i < V; i++)
adj.add(new LinkedList<>());
}
void addEdge(int u, int v) {
adj.get(u).add(v);
adj.get(v).add(u);
}
}
static List<Integer> findEulerianPath(Graph g) {
Stack<Integer> stack = new Stack<>();
List<Integer> path = new ArrayList<>();
int start = 0;
for (int i = 0; i < g.V; i++) {
if (g.adj.get(i).size() % 2 == 1) { // odd degree
start = i;
break;
}
}
stack.push(start);
while (!stack.isEmpty()) {
int u = stack.peek();
if (g.adj.get(u).size() == 0) {
path.add(u);
stack.pop();
} else {
int v = g.adj.get(u).poll();
g.adj.get(v).remove((Integer) u); // remove reverse edge
stack.push(v);
}
}
Collections.reverse(path);
return path;
}
public static void main(String[] args) {
Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.addEdge(4, 0);
List<Integer> path = findEulerianPath(g);
System.out.println("Eulerian Path or Circuit:");
System.out.println(path);
}
}