Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to **N, **and a  2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are  connected adjacent to any one of the nodes present in the set.

Examples :

Input:_ N = 4, Edges[][2] = {{2, 3}, {1, 3}, {4, 2}, {1, 2}}_

Output:_ 3 2_

Explanation:_ Connections specified in the above graph are as follows:_

_   1_

_ /   _

2 – 3

|

4

Selecting the set {2, 3} satisfies the required conditions.

Input:_ N = 5, Edges[][2] = {{2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}}_

Output:_ 1_

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Approach: **The given problem can be solved based on the following observations:

  • Assume a node to be the source node, then the distance of each vertex from the source node will be either odd or even.
  • Split the nodes into two different sets based on parity, the size of at least one of the sets will not exceed** N/2**. Since each node of some parity is connected to at least one node of opposite parity, the criteria of choosing at most N/2 nodes is satisfied.

Follow the steps below to solve the problem:

  • Assume any vertex to be the source node.
  • Initialize two sets, say evenParity and **oddParity, **to store the nodes having even and odd distances from the source node respectively.
  • Perform BFS Traversal on the given graph and split the vertices into two different sets depending on the parity of their distances from the source:
  • If the distance of each connected node from the source node is **odd, **then  insert the current node in the set oddParity.
  • If the distance of each connected node from the source node is **even, ** then  insert the current node in the set evenParity.
  • After completing the above steps, print the elements of the set with the minimum size.

#graph #hash #mathematical #tree #node #node.js

Find A Set Of At Most N/2 Nodes From A Graph Such That All Remaining Nodes Are Directly
1.20 GEEK