Skip to content

Commit e5b6152

Browse files
authored
Create Add Edges to Make Degrees of All Nodes Even.java
1 parent d07aabc commit e5b6152

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public boolean isPossible(int n, List<List<Integer>> edges) {
3+
Map<Integer, Set<Integer>> graph = new HashMap<>();
4+
for (List<Integer> edge : edges) {
5+
graph.computeIfAbsent(edge.get(0), k -> new HashSet<>()).add(edge.get(1));
6+
graph.computeIfAbsent(edge.get(1), k -> new HashSet<>()).add(edge.get(0));
7+
}
8+
List<Integer> nodeWithOddEdges = graph.entrySet()
9+
.stream()
10+
.filter(e -> e.getValue().size() % 2 != 0)
11+
.map(Map.Entry::getKey)
12+
.collect(Collectors.toList());
13+
if (nodeWithOddEdges.size() == 0) {
14+
return true;
15+
}
16+
if (nodeWithOddEdges.size() == 2) {
17+
Integer nodeOne = nodeWithOddEdges.get(0);
18+
Integer nodeTwo = nodeWithOddEdges.get(1);
19+
if (!hasEdge(graph, nodeOne, nodeTwo)) {
20+
return true;
21+
}
22+
for (int i = 1; i <= n; i++) {
23+
if (i == nodeOne || i == nodeTwo) {
24+
continue;
25+
}
26+
if (!hasEdge(graph, i, nodeOne) && !hasEdge(graph, i, nodeTwo)) {
27+
return true;
28+
}
29+
}
30+
}
31+
if (nodeWithOddEdges.size() == 4) {
32+
Integer nodeOne = nodeWithOddEdges.get(0);
33+
Integer nodeTwo = nodeWithOddEdges.get(1);
34+
Integer nodeThree = nodeWithOddEdges.get(2);
35+
Integer nodeFour = nodeWithOddEdges.get(3);
36+
if ((!hasEdge(graph, nodeOne, nodeTwo) && !hasEdge(graph, nodeThree, nodeFour)) ||
37+
(!hasEdge(graph, nodeOne, nodeThree) && !hasEdge(graph, nodeTwo, nodeFour)) ||
38+
(!hasEdge(graph, nodeOne, nodeFour) && !hasEdge(graph, nodeTwo, nodeThree))) {
39+
return true;
40+
}
41+
}
42+
return false;
43+
}
44+
45+
private static boolean hasEdge(Map<Integer, Set<Integer>> graph, int nodeOne, int nodeTwo) {
46+
return graph.getOrDefault(nodeOne, new HashSet<>()).contains(nodeTwo);
47+
}
48+
}

0 commit comments

Comments
 (0)