LeetCode 题解工作台
受限条件下可到达节点的数目
现有一棵由 n 个节点组成的无向树,节点编号从 0 到 n - 1 ,共有 n - 1 条边。 给你一个二维整数数组 edges ,长度为 n - 1 ,其中 edges[i] = [a i , b i ] 表示树中节点 a i 和 b i 之间存在一条边。另给你一个整数数组 restricted …
7
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们首先根据给定的边构建一个邻接表 ,其中 表示与节点 相邻的节点列表。然后我们定义一个哈希表 ,用于记录受限节点或者已经访问过的节点,初始时将受限节点加入到 中。 接下来我们定义一个深度优先搜索函数 ,表示从节点 出发,可以到达的节点数。在 函数中,我们首先将节点 加入到 中,然后遍历节点 的相邻节点 ,如果 不在 中,我们递归调用 ,并将返回值加到结果中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
现有一棵由 n 个节点组成的无向树,节点编号从 0 到 n - 1 ,共有 n - 1 条边。
给你一个二维整数数组 edges ,长度为 n - 1 ,其中 edges[i] = [ai, bi] 表示树中节点 ai 和 bi 之间存在一条边。另给你一个整数数组 restricted 表示 受限 节点。
在不访问受限节点的前提下,返回你可以从节点 0 到达的 最多 节点数目。
注意,节点 0 不 会标记为受限节点。
示例 1:
输入:n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5] 输出:4 解释:上图所示正是这棵树。 在不访问受限节点的前提下,只有节点 [0,1,2,3] 可以从节点 0 到达。
示例 2:
输入:n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] 输出:3 解释:上图所示正是这棵树。 在不访问受限节点的前提下,只有节点 [0,5,6] 可以从节点 0 到达。
提示:
2 <= n <= 105edges.length == n - 1edges[i].length == 20 <= ai, bi < nai != biedges表示一棵有效的树1 <= restricted.length < n1 <= restricted[i] < nrestricted中的所有值 互不相同
解题思路
方法一:DFS
我们首先根据给定的边构建一个邻接表 ,其中 表示与节点 相邻的节点列表。然后我们定义一个哈希表 ,用于记录受限节点或者已经访问过的节点,初始时将受限节点加入到 中。
接下来我们定义一个深度优先搜索函数 ,表示从节点 出发,可以到达的节点数。在 函数中,我们首先将节点 加入到 中,然后遍历节点 的相邻节点 ,如果 不在 中,我们递归调用 ,并将返回值加到结果中。
最后我们返回 即可。
时间复杂度 ,空间复杂度 。其中 为节点数。
class Solution:
def reachableNodes(
self, n: int, edges: List[List[int]], restricted: List[int]
) -> int:
def dfs(i: int) -> int:
vis.add(i)
return 1 + sum(j not in vis and dfs(j) for j in g[i])
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = set(restricted)
return dfs(0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate shows an understanding of tree traversal techniques like DFS or BFS.
- question_mark
Candidate is able to use hash sets for efficient lookups, avoiding restricted nodes.
- question_mark
Candidate demonstrates optimization skills by considering early termination in traversal.
常见陷阱
外企场景- error
Failing to correctly handle the restricted nodes, causing the traversal to incorrectly include invalid nodes.
- error
Incorrectly managing the visited set, leading to cycles or revisiting nodes.
- error
Not optimizing the traversal, leading to unnecessary checks or excessive computation.
进阶变体
外企场景- arrow_right_alt
What if there are additional restrictions such as time limits on traversal?
- arrow_right_alt
Can this problem be solved with a Union-Find approach instead of DFS or BFS?
- arrow_right_alt
How would the solution change if there were multiple starting nodes?