查找均匀距离处的节点对数 |第 2 组(使用 BFS)
给定一个连通的无环图,其中有N个节点,编号从 1 到 N 和N-1 条边,找出彼此距离相等的节点对。
注意:该图以邻接表的形式表示。
例子:
Input: N = 3, graph = {{}, {2}, {1, 3}, {2}}
Output:1
Explanation: Here there are three pairs {1, 2}, {1, 3}
and {2, 3} and only {1, 3} has even distance between them.
i.e., 1
/
2
/
3
Input: N = 5, graph = {{}, {2, 4}, {1, 3}, {2}, {1, 5}, {4}}
Output: 4
Explanation: There are four pairs {1, 3}, {1, 5}, {2, 4}
and {3, 5} which has even distance.
方法:本文的 DFS 方法已在本文的Set-1中讨论。在这里,我们将使用 BFS Traversal Of Graph 来解决基于以下思想的问题:
Start traversing from any node (say 1) as the root of the graph and store the number of nodes in odd and even numbered level. The nodes in even numbered level are distance away from each other. The same is true for nodes in odd numbered levels.
按照下面提到的步骤来实现这个想法:
- 创建一个数组来跟踪所有访问过的节点。
- 使用队列对图进行 BFS 遍历。
- 初始推入队列中的第一个节点,然后遍历并将其尚未访问的邻居推入队列,并以此方式继续BFS。
- 计算偶数级别(例如X )和奇数级别(例如Y )中的节点数。
- 答案将是从 X 中选择任意两个元素(即 (X * (X – 1)) / 2) 和从 Y 中选择任意两个元素(即 (Y * (Y – 1)))/ 2)。
下面是上述方法的实现:
C++
时间复杂度: O(V+E) = O(N)。如给定的 V = 节点数 = N,E = 边数 = N-1。
辅助空间: O(N)