-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathHamiltonianRoutesCount.java
72 lines (63 loc) · 1.51 KB
/
HamiltonianRoutesCount.java
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
import java.util.HashMap;
import java.util.Map;
// http://blog.sina.com.cn/s/blog_5123df350101b54k.html
public class HamiltonianRoutesCount {
public int solution(int[] A) {
if (isAllRoadsConnectsDistinctTowns(A)
&& isAllTownsVisitedOnceOrThrice(A)
&& isAllRoadsVisitedTwice(A)) {
return 3;
} else {
return -2;
}
}
boolean isAllRoadsConnectsDistinctTowns(int[] A) {
for (int i = 0; i < A.length; i++) {
if (A[i] == A[(i + 1) % A.length]) {
return false;
}
}
return true;
}
boolean isAllTownsVisitedOnceOrThrice(int[] A) {
int townNum = A.length / 2 + 1;
int[] townCounts = new int[townNum];
for (int town : A) {
townCounts[town]++;
}
for (int townCount : townCounts) {
if (townCount != 1 && townCount != 3) {
return false;
}
}
return true;
}
boolean isAllRoadsVisitedTwice(int[] A) {
Map<Road, Integer> road2count = new HashMap<Road, Integer>();
for (int i = 0; i < A.length; i++) {
Road road = new Road(A[i], A[(i + 1) % A.length]);
if (!road2count.containsKey(road)) {
road2count.put(road, 0);
}
road2count.put(road, road2count.get(road) + 1);
}
return road2count.values().stream().allMatch(count -> count == 2);
}
}
class Road {
int town1;
int town2;
Road(int t1, int t2) {
this.town1 = Math.min(t1, t2);
this.town2 = Math.max(t1, t2);
}
@Override
public int hashCode() {
return town1 * town2;
}
@Override
public boolean equals(Object obj) {
Road other = (Road) obj;
return town1 == other.town1 && town2 == other.town2;
}
}