Hard
,Graph
1579. Remove Max Number of Edges to Keep Graph Fully Traversable
Alice and Bob have an undirected graph of n
nodes and three types of edges:
Given an array edges
where edges[i]
= [
Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.
Example 1:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]
Output: 2
Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.
Example 2:
Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]
Output: 0
Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.
Example 3:
Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]
Output: -1
Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.
Constraints:
n
<= 105edges.length
<= min(105, 3 * n
* (n
- 1) / 2)edges[i].length
== 3n
class Solution:
def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:
parents = list(range(n + 1))
def find(x):
if parents[x] != x:
parents[x] = find(parents[x])
return parents[x]
def union(x, y):
x, y = find(x), find(y)
if x == y: return False
parents[x] = y
return True
ans = alice_count = bob_count = 0
for t, u, v in edges:
if t == 3:
if union(u, v):
alice_count += 1
bob_count += 1
else:
ans += 1
temp = parents[:]
for t, u, v in edges:
if t == 1:
if union(u, v):
alice_count += 1
else:
ans += 1
parents = temp
for t, u, v in edges:
if t == 2:
if union(u, v):
bob_count += 1
else:
ans += 1
return ans if alice_count == bob_count == n - 1 else -1
Yen-Chi ChenMon, May 1, 2023
function maxNumEdgesToRemove(n, edges) {
const alice = new UnionFind(n);
const bob = new UnionFind(n);
let count = 0;
for (const [type, v1, v2] of edges) {
if (type === 3 && alice.union(v1, v2) && bob.union(v1, v2)) {
count++;
}
}
for (const [type, v1, v2] of edges) {
if (type === 1 && alice.union(v1, v2)) count++;
if (type === 2 && bob.union(v1, v2)) count++;
}
if (alice.size !== 1 || bob.size !== 1) return -1;
return edges.length - count;
}
class UnionFind {
constructor(n) {
this.parent = new Array(n + 1).fill().map((_, i) => i);
this.size = n;
}
find(x) {
if (x === this.parent[x]) return x;
return (this.parent[x] = this.find(this.parent[x]));
}
union(x, y) {
const rootX = this.find(x);
const rootY = this.find(y);
if (rootX === rootY) return false;
this.parent[rootX] = rootY;
this.size--;
return true;
}
}
MarsgoatFri, May 5, 2023