Find count of pair of nodes at even distance | Set 2 (Using BFS)
Last Updated :
28 Jun, 2022
Given a connected acyclic graph with N nodes numbered from 1 to N and N-1 edges, find out the pair of nodes that are at even distance from each other.
Note: The graph is represented in the form of an adjacency list.
Examples:
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.
Approach: The DFS approach of this article is already discussed in Set-1 of this article. Here we will be using the BFS Traversal Of Graph to solve the problem based on the following idea:
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.
Follow the steps mentioned below to implement the idea:
- Create an array to keep track of all the visited nodes.
- Using queue do BFS traversal of the graph.
- Initially push the first node in the queue and then traverse and push its neighbours which are not yet visited into the queue and continue the BFS in this way.
- Count the number of nodes in even numbered levels (say X) and odd numbered levels (say Y).
- The answer will be the sum of the number of ways to choose any two elements from X (i.e (X * (X – 1)) / 2)and any two elements from Y (i.e. (Y * (Y – 1)) / 2 ).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countOfNodes(vector< int > graph[], int n)
{
vector< int > vis(n + 1);
queue<pair< int , int > > q;
long long _0 = 0, _1 = 0;
q.push({ 1, 0 });
while (!q.empty()) {
vis[q.front().first] = 1;
for ( auto child : graph[q.front().first]) {
if (!vis[child])
q.push({ child, 1 - q.front().second });
}
if (q.front().second)
_1++;
else
_0++;
q.pop();
}
int ans
= (_0 * (_0 - 1)) / 2
+ (_1 * (_1 - 1)) / 2;
return ans;
}
int main()
{
int N = 3;
vector< int > graph[N + 1];
graph[1].push_back(2);
graph[2].push_back(1);
graph[2].push_back(3);
graph[3].push_back(2);
cout << countOfNodes(graph, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Pair {
int x;
int y;
public Pair( int x, int y)
{
this .x = x;
this .y = y;
}
}
class GFG {
static void addEdge(ArrayList<ArrayList<Integer> > adj,
int u, int v)
{
adj.get(u).add(v);
}
public static long
countOfNodes(ArrayList<ArrayList<Integer> > graph,
int n)
{
int vis[] = new int [n + 1 ];
Queue<Pair> q = new LinkedList<>();
long _0 = 0 , _1 = 0 ;
q.add( new Pair( 1 , 0 ));
while (!q.isEmpty()) {
vis[q.peek().x] = 1 ;
for (Integer child : graph.get(q.peek().x)) {
if (vis[child] == 0 )
q.add( new Pair(child, 1 - q.peek().y));
}
if (q.peek().y != 0 )
_1++;
else
_0++;
q.poll();
}
long ans
= (_0 * (_0 - 1 )) / 2 + (_1 * (_1 - 1 )) / 2 ;
return ans;
}
public static void main(String[] args)
{
int N = 3 ;
ArrayList<ArrayList<Integer> > graph
= new ArrayList<ArrayList<Integer> >(N + 1 );
for ( int i = 0 ; i < N + 1 ; i++)
graph.add( new ArrayList<Integer>());
addEdge(graph, 1 , 2 );
addEdge(graph, 2 , 1 );
addEdge(graph, 2 , 3 );
addEdge(graph, 3 , 2 );
System.out.print(countOfNodes(graph, N));
}
}
|
Python3
def countOfNodes(graph, n):
vis = [ None ] * (n + 1 )
q = []
_0 = 0
_1 = 0
q.append([ 1 , 0 ])
while ( len (q) > 0 ):
front = q.pop( 0 )
vis[front[ 0 ]] = 1
for child in graph[front[ 0 ]]:
if vis[child] is None :
q.append([child, 1 - front[ 1 ]])
if (front[ 1 ]):
_1 + = 1
else :
_0 + = 1
ans = (_0 * (_0 - 1 )) / / 2 + (_1 * (_1 - 1 )) / / 2
return ans
N = 3
graph = [[]]
graph.append([ 2 ])
graph.append([ 1 , 3 ])
graph.append([ 2 ])
print (countOfNodes(graph, N))
|
C#
using System;
using System.Collections.Generic;
class Pair {
public int x;
public int y;
public Pair( int x, int y)
{
this .x = x;
this .y = y;
}
}
class GFG {
static void addEdge(List<List< int > > adj, int u, int v)
{
adj[u].Add(v);
}
public static long countOfNodes(List<List< int > > graph,
int n)
{
int [] vis = new int [n + 1];
Queue<Pair> q = new Queue<Pair>();
long _0 = 0, _1 = 0;
q.Enqueue( new Pair(1, 0));
while (q.Count > 0) {
vis[q.Peek().x] = 1;
foreach ( int child in graph[q.Peek().x])
{
if (vis[child] == 0)
q.Enqueue(
new Pair(child, 1 - q.Peek().y));
}
if (q.Peek().y != 0)
_1++;
else
_0++;
q.Dequeue();
}
long ans
= (_0 * (_0 - 1)) / 2 + (_1 * (_1 - 1)) / 2;
return ans;
}
public static void Main( string [] args)
{
int N = 3;
List<List< int > > graph
= new List<List< int > >(N + 1);
for ( int i = 0; i < N + 1; i++)
graph.Add( new List< int >());
addEdge(graph, 1, 2);
addEdge(graph, 2, 1);
addEdge(graph, 2, 3);
addEdge(graph, 3, 2);
Console.Write(countOfNodes(graph, N));
}
}
|
Javascript
<script>
function countOfNodes(graph, n)
{
let vis = new Array(n + 1);
let q = [];
let _0 = 0, _1 = 0;
q.push([1, 0 ]);
while (q.length>0) {
let front = q.shift();
vis[front[0]] = 1;
for (let child of graph[front[0]]) {
if (!vis[child])
q.push([ child, 1 - front[1] ]);
}
if (front[1])
_1++;
else
_0++;
}
let ans
= (_0 * (_0 - 1)) / 2
+ (_1 * (_1 - 1)) / 2;
return ans;
}
let N = 3;
let graph = new Array(N + 1).fill([]).map(()=> new Array());
graph[1].push(2);
graph[2].push(1);
graph[2].push(3);
graph[3].push(2);
document.write(countOfNodes(graph, N));
</script>
|
Time Complexity: O(V+E) = O(N). As V = number of nodes = N, E = number of edges = N-1 as given.
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...