Skip to content

Commit 85ce312

Browse files
committed
Added Hierholzer Algorith to find Eulerian Path
1 parent 60098bb commit 85ce312

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

src/main/java/com/thealgorithms/graph/HierholzerEulerianPath.java

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,14 +120,18 @@ public List<Integer> findEulerianPath() {
120120
}
121121

122122
int startNode = determineStartNode(inDegree, outDegree);
123-
if (startNode == -1) return new ArrayList<>();
123+
if (startNode == -1) {
124+
return new ArrayList<>();
125+
}
124126

125127
if (!allNonZeroDegreeVerticesWeaklyConnected(startNode, n, outDegree, inDegree)) {
126128
return new ArrayList<>();
127129
}
128130

129131
List<Integer> path = buildHierholzerPath(startNode, n);
130-
if (path.size() != edgeCount + 1) return new ArrayList<>();
132+
if (path.size() != edgeCount + 1) {
133+
return new ArrayList<>();
134+
}
131135

132136
return rotateEulerianCircuitIfNeeded(path, outDegree, inDegree);
133137
}
@@ -205,10 +209,11 @@ private List<Integer> rotateEulerianCircuitIfNeeded(List<Integer> path, int[] ou
205209
int endCount = 0;
206210
for (int i = 0; i < outDegree.length; i++) {
207211
int diff = outDegree[i] - inDegree[i];
208-
if (diff == 1)
212+
if (diff == 1) {
209213
startCount++;
210-
else if (diff == -1)
214+
} else if (diff == -1) {
211215
endCount++;
216+
}
212217
}
213218

214219
if (startCount == 0 && endCount == 0 && !path.isEmpty()) {
@@ -223,14 +228,20 @@ else if (diff == -1)
223228
if (preferredStart != -1 && path.get(0) != preferredStart) {
224229
int idx = 0;
225230
for (int node : path) {
226-
if (node == preferredStart) break;
231+
if (node == preferredStart) {
232+
break;
233+
}
227234
idx++;
228235
}
229236

230237
if (idx > 0) {
231238
List<Integer> rotated = new ArrayList<>();
232-
for (int i = idx; i < path.size(); i++) rotated.add(path.get(i));
233-
for (int i = 0; i < idx; i++) rotated.add(path.get(i));
239+
for (int i = idx; i < path.size(); i++) {
240+
rotated.add(path.get(i));
241+
}
242+
for (int i = 0; i < idx; i++) {
243+
rotated.add(path.get(i));
244+
}
234245
path = rotated;
235246
}
236247
}

0 commit comments

Comments
 (0)