-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEulerTour.java
More file actions
60 lines (51 loc) · 1.37 KB
/
Copy pathEulerTour.java
File metadata and controls
60 lines (51 loc) · 1.37 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
package templates;
import java.io.*;
import java.util.*;
// ************************ FOR TREES **************************
public class EulerTour {
int[] start, end;
ArrayList<ArrayList<Integer>> adj;
int timer;
public EulerTour(int n) {
adj = new ArrayList<>();
for (int i = 0; i < n; i++)
adj.add(new ArrayList<>());
start = new int[n];
end = new int[n];
timer = 0;
}
public void addEdge(int a, int b) {
adj.get(a).add(b);
adj.get(b).add(a);
}
// Euler tour
public void tour(int v, int par) {
start[v] = timer++;
for (int u : adj.get(v)) {
if (u != par)
tour(u, v);
}
end[v] = timer;
}
// Euler tour using arraydeque in place of recursive dfs calls
public void tour2(int v) {
boolean[] vis = new boolean[start.length];
ArrayDeque<Integer> l = new ArrayDeque<>();
l.add(v);
while (l.size() > 0) {
int cur = l.getLast();
if (vis[cur]) {
end[cur] = timer;
l.removeLast();
continue;
}
start[cur] = timer++;
vis[cur] = true;
for (int u : adj.get(cur)) {
if (!vis[u]) {
l.add(u);
}
}
}
}
}