Find count of pair of nodes at even distance | Set 2 (Using BFS)
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
/
3Input: 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++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the count of nodes at // even distance using BFS method int countOfNodes(vector< int > graph[], int n) { // Declare one vector to check that // element is visited or not vector< int > vis(n + 1); // Declare one queue queue<pair< int , int > > 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< int > 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; } |
Java
// Java code to implement the approach import java.io.*; import java.util.*; // User defined Pair class class Pair { int x; int y; // Constructor 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); } // Function to find the count of nodes at // even distance using BFS method public static long countOfNodes(ArrayList<ArrayList<Integer> > graph, int n) { // Declare one vector to check that // element is visited or not int vis[] = new int [n + 1 ]; // Declare one queue Queue<Pair> q = new LinkedList<>(); long _0 = 0 , _1 = 0 ; // Initially push the first node with its // level as even in the queue q.add( new Pair( 1 , 0 )); // Run this loop until q is not empty while (!q.isEmpty()) { vis[q.peek().x] = 1 ; // Check for the adjacent nodes for (Integer child : graph.get(q.peek().x)) { // Check only if adjacent node // is not visited if (vis[child] == 0 ) q.add( new Pair(child, 1 - q.peek().y)); } if (q.peek().y != 0 ) _1++; else _0++; q.poll(); } // Answer will be the sum of the number // of ways to choose any two elements // of even and odd type long ans = (_0 * (_0 - 1 )) / 2 + (_1 * (_1 - 1 )) / 2 ; return ans; } // Driver code public static void main(String[] args) { int N = 3 ; // Creating adjacency list for the graph 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 ); // Function call System.out.print(countOfNodes(graph, N)); } } // This code is contributed by Rohit Pradhan |
Python3
# Python3 code to implement the above approach # Function to find the count of nodes at # even distance using BFS method def countOfNodes(graph, n): # Declare one vector to check that # element is visited or not vis = [ None ] * (n + 1 ) # Declare one queue q = [] _0 = 0 _1 = 0 # Initially push the first node with its # level as even in the queue q.append([ 1 , 0 ]) # Run this loop until q is not empty while ( len (q) > 0 ): front = q.pop( 0 ) vis[front[ 0 ]] = 1 # Check for the adjacent nodes for child in graph[front[ 0 ]]: # Check only if adjacent node # is not visited if vis[child] is None : q.append([child, 1 - front[ 1 ]]) if (front[ 1 ]): _1 + = 1 else : _0 + = 1 # Answer will be the sum of the number # of ways to choose any two elements # of even and odd type ans = (_0 * (_0 - 1 )) / / 2 + (_1 * (_1 - 1 )) / / 2 return ans # Driver code N = 3 # Creating adjacency list for the graph graph = [[]] graph.append([ 2 ]) graph.append([ 1 , 3 ]) graph.append([ 2 ]) # Function call print (countOfNodes(graph, N)) # This code is contributed by phasing17 |
C#
// C# code to implement the approach using System; using System.Collections.Generic; // User defined Pair class class Pair { public int x; public int y; // Constructor 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); } // Function to find the count of nodes at // even distance using BFS method public static long countOfNodes(List<List< int > > graph, int n) { // Declare one vector to check that // element is visited or not int [] vis = new int [n + 1]; // Declare one queue Queue<Pair> q = new Queue<Pair>(); long _0 = 0, _1 = 0; // Initially push the first node with its // level as even in the queue q.Enqueue( new Pair(1, 0)); // Run this loop until q is not empty while (q.Count > 0) { vis[q.Peek().x] = 1; // Check for the adjacent nodes foreach ( int child in graph[q.Peek().x]) { // Check only if adjacent node // is not visited if (vis[child] == 0) q.Enqueue( new Pair(child, 1 - q.Peek().y)); } if (q.Peek().y != 0) _1++; else _0++; q.Dequeue(); } // Answer will be the sum of the number // of ways to choose any two elements // of even and odd type long ans = (_0 * (_0 - 1)) / 2 + (_1 * (_1 - 1)) / 2; return ans; } // Driver code public static void Main( string [] args) { int N = 3; // Creating adjacency list for the graph 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); // Function call Console.Write(countOfNodes(graph, N)); } } // This code is contributed by phasing17 |
Javascript
<script> // JavaScript code to implement the above approach // Function to find the count of nodes at // even distance using BFS method function countOfNodes(graph, n) { // Declare one vector to check that // element is visited or not let vis = new Array(n + 1); // Declare one queue let q = []; let _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.length>0) { let front = q.shift(); vis[front[0]] = 1; // Check for the adjacent nodes for (let child of graph[front[0]]) { // Check only if adjacent node // is not visited if (!vis[child]) q.push([ child, 1 - front[1] ]); } if (front[1]) _1++; else _0++; } // Answer will be the sum of the number // of ways to choose any two elements // of even and odd type let ans = (_0 * (_0 - 1)) / 2 + (_1 * (_1 - 1)) / 2; return ans; } // Driver code let N = 3; // Creating adjacency list for the graph 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); // Function call document.write(countOfNodes(graph, N)); // This code is contributed by shinjanpatra </script> |
1
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)
Please Login to comment...