Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
[ad_1]
Given a related acyclic graph with N nodes numbered from 1 to N and N-1 edges, discover out the pair of nodes which are at even distance from one another.
Observe: The graph is represented within the type of an adjacency record.
Examples:
Enter: N = 3, graph = {{}, {2}, {1, 3}, {2}}
Output:1
Clarification: Right here there are three pairs {1, 2}, {1, 3}
and {2, 3} and solely {1, 3} has even distance between them.
i.e., 1
/
2
/
3Enter: N = 5, graph = {{}, {2, 4}, {1, 3}, {2}, {1, 5}, {4}}
Output: 4
Clarification: There are 4 pairs {1, 3}, {1, 5}, {2, 4}
and {3, 5} which has even distance.
Strategy: The DFS method of this text is already mentioned in Set-1 of this text. Right here we will probably be utilizing the BFS Traversal Of Graph to unravel the issue primarily based on the next concept:
Begin traversing from any node (say 1) as the basis of the graph and retailer the variety of nodes in odd and even numbered degree. The nodes in even numbered degree are distance away from one another. The identical is true for nodes in odd numbered ranges.
Comply with the steps talked about under to implement the concept:
Beneath is the implementation of the above method:
|
Time Complexity: O(V+E) = O(N). As V = variety of nodes = N, E = variety of edges = N-1 as given.
Auxiliary Area: O(N)
[ad_2]