forked from liuyubobobo/Play-with-Graph-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEulerLoop.java
More file actions
57 lines (44 loc) · 1.29 KB
/
EulerLoop.java
File metadata and controls
57 lines (44 loc) · 1.29 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
import java.util.ArrayList;
import java.util.Stack;
public class EulerLoop {
private Graph G;
public EulerLoop(Graph G){
this.G = G;
}
private boolean hasEulerLoop(){
CC cc = new CC(G);
if(cc.count() > 1) return false;
for(int v = 0; v < G.V(); v ++)
if(G.degree(v) % 2 == 1) return false;
return true;
}
public ArrayList<Integer> result(){
ArrayList<Integer> res = new ArrayList<>();
if(!hasEulerLoop()) return res;
Graph g = (Graph)G.clone();
Stack<Integer> stack = new Stack<>();
int curv = 0;
stack.push(curv);
while(!stack.isEmpty()){
if(g.degree(curv) != 0){
stack.push(curv);
int w = g.adj(curv).iterator().next();
g.removeEdge(curv, w);
curv = w;
}
else{
res.add(curv);
curv = stack.pop();
}
}
return res;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
EulerLoop el = new EulerLoop(g);
System.out.println(el.result());
Graph g2 = new Graph("g2.txt");
EulerLoop el2 = new EulerLoop(g2);
System.out.println(el2.result());
}
}