查找均匀距离处的节点对数 |第 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++
// C++ code to implement the approach
#include
using namespace std;
// Function to find the count of nodes at
// even distance using BFS method
int countOfNodes(vector graph[], int n)
{
// Declare one vector to check that
// element is visited or not
vector vis(n + 1);
// Declare one queue
queue > q;
long long _0 = 0, _1 = 0;
// Initially push the first node with its
// level as even in the queue
q.push({ 1, 0 });
// Run this loop until q is not empty
while (!q.empty()) {
vis[q.front().first] = 1;
// Check for the adjacent nodes
for (auto child : graph[q.front().first]) {
// Check only if adjacent node
// is not visited
if (!vis[child])
q.push({ child, 1 - q.front().second });
}
if (q.front().second)
_1++;
else
_0++;
q.pop();
}
// Answer will be the sum of the number
// of ways to choose any two elements
// of even and odd type
int ans
= (_0 * (_0 - 1)) / 2
+ (_1 * (_1 - 1)) / 2;
return ans;
}
// Driver code
int main()
{
int N = 3;
// Creating adjacency list for the graph
vector graph[N + 1];
graph[1].push_back(2);
graph[2].push_back(1);
graph[2].push_back(3);
graph[3].push_back(2);
// Function call
cout << countOfNodes(graph, N);
return 0;
}
1
时间复杂度: O(V+E) = O(N)。如给定的 V = 节点数 = N,E = 边数 = N-1。
辅助空间: O(N)