Count Connected Subgraphs with Even Node Sum Problem
Description
LeetCode Problem 3910.
You are given an undirected graph with n nodes labeled from 0 to n - 1. Node i has a value of nums[i], which is either 0 or 1. The edges of the graph are given by a 2D array edges where edges[i] = [u_i, v_i] represents an edge between node u_i and node v_i.
For a non-empty subset s of nodes in the graph, we consider the induced subgraph of s generated as follows:
- We keep only the nodes in
s. - We keep only the edges whose two endpoints are both in
s.
Return an integer representing the number of non-empty subsets s of nodes in the graph such that:
- The induced subgraph of
sis connected. - The sum of node values in
sis even.
Example 1:
Input: nums = [1,0,1], edges = [[0,1],[1,2]]
Output: 2
Explanation:
s connected? sum of node values counted?
[0] Yes 1 No
[1] Yes 0 Yes
[2] Yes 1 No
[0,1] Yes 1 No
[0,2] No, node 0 and node 2 are disconnected. 2 No
[1,2] Yes 1 No
[0,1,2] Yes 2 Yes
Example 2:
Input: nums = [1], edges = []
Output: 0
Explanation:
s connected? sum of node values counted?
[0] Yes 1 No
Constraints:
1 <= n == nums.length <= 13nums[i]is 0 or 1.0 <= edges.length <= n * (n - 1) / 2edges[i] = [u_i, v_i]0 <= u_i < v_i < n- All edges are distinct.
Solution
Approach: Bitmask Enumeration + DFS
There are at most 13 nodes, so we can try every non-empty subset of nodes. Represent a subset as a bitmask sub, where bit i is 1 when node i is in it.
For each subset, first add up the values of its nodes and skip it if the sum is odd. Otherwise, check that the induced subgraph is connected with a DFS. Keep a bitmask vis that starts as the complement of sub, so nodes outside the subset count as already visited. Run a DFS from any node of the subset (for example its highest set bit), moving only to unvisited neighbors. The subset is connected exactly when vis ends up with all n bits set, because every node of the subset was reached.
Count the subsets that pass both checks.
Complexity: time O(2^n (n + m)) and space O(n + m), where n and m are the numbers of nodes and edges.
class Solution:
def evenSumSubgraphs(self, nums: List[int], edges: List[List[int]]) -> int:
n = len(nums)
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
m = (1 << n) - 1
ans = 0
for sub in range(1, m + 1):
s = sum(x for i, x in enumerate(nums) if sub >> i & 1)
if s % 2:
continue
vis = m ^ sub
def dfs(u: int) -> None:
nonlocal vis
vis |= 1 << u
for v in g[u]:
if (vis >> v & 1) == 0:
dfs(v)
dfs(sub.bit_length() - 1)
if vis == m:
ans += 1
return ans