[LeetCode] Reachable Nodes With Restrictions

2368. Reachable Nodes With Restrictions

There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.

Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.

Note that node 0 will not be a restricted node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int reachableNodes(int n, vector<vector<int>>& edges, vector<int>& B) {
unordered_set<int> us(begin(B), end(B));
vector<vector<int>> adj(n);
for(auto& e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
unordered_set<int> vis;
queue<int> q;
vis.insert(0);
q.push(0);
while(!q.empty()) {
int u = q.front(); q.pop();
for(auto& v : adj[u]) {
if(vis.count(v)) continue;
if(us.count(v)) continue;
vis.insert(v);
q.push(v);
}
}

return vis.size();
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/07/PS/LeetCode/reachable-nodes-with-restrictions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.