题目描述
现有一棵由 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 到达。
输入:n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1] 输出:3 解释:上图所示正是这棵树。 在不访问受限节点的前提下,只有节点 [0,5,6] 可以从节点 0 到达。
解体思路
遇到这种树种遍历的问题,一般都是使用DFS/BFS进行解决;此题也不例外,首先我们根据给定的边构建一个邻接表 graph,其中 graph[i]表示与节点i相邻的节点列表。然后我们定义一个哈希表visit,用于记录受限节点或者已经访问过的节点,初始时将受限节点加入到 visit中。
接下来我们定义一个深度优先搜索函数dfs(i),表示从节点i出发,可以到达的节点数。在dfs(i)函数中,我们首先将节点i加入到visit中,然后遍历节点i的相邻节点j,如果j不在visit中,我们递归调用 dfs(j),并将返回值加到结果中。
最后我们返回 dfs(0)即可。
复杂度分析
时间复杂度:O(n), n为节点数
空间复杂度:O(n)
代码
#include <vector>
#include <unordered_set>
#include <iostream>
#include <string_view>
using namespace std;
class Solution
{
private:
int ans;
unordered_set<int> unachieveable;
vector<vector<int>> graph;
void dfs(int n)
{
unachieveable.insert(n);
ans++;
for (int next : graph[n])
{
if (!unachieveable.count(next))
{
dfs(next);
}
}
}
public:
int reachableNodes(int n, vector<vector<int>> &edges, vector<int> &restricted)
{
ans = 0;
graph.resize(n);
for (vector<int> &edge : edges)
{
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
for (int t : restricted)
{
unachieveable.insert(t);
}
dfs(0);
return ans;
}
};
int main()
{
cout << "LeetCode" << endl;
int n = 7;
vector<vector<int>> edges = {{0, 1}, {1, 2}, {3, 1}, {4, 0}, {0, 5}, {5, 6}};
vector<int> restricted = {4, 5};
int res = Solution().reachableNodes(n, edges, restricted);
cout << res << endl;
n = 7;
edges = {{0, 1}, {0, 2}, {0, 5}, {0, 4}, {3, 2}, {6, 5}};
restricted = {4, 2, 1};
res = Solution().reachableNodes(n, edges, restricted);
cout << res << endl;
}