LeetCode每日一题【c++版】- leetcode 2368. 受限条件下可到达节点的数目【dfs】

34 篇文章 0 订阅
17 篇文章 0 订阅
本文详细描述了一种算法,通过构建邻接表并运用DFS遍历,在无向树中计算节点0可到达的最大节点数,避开受限节点。
摘要由CSDN通过智能技术生成

题目描述

        现有一棵由 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;
}

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值