Given a connected graph with N vertices. The task is to select k(k must be less than or equals to n/2, not necessarily minimum) vertices from the graph such that all these selected vertices are connected to at least one of the non selected vertex. In case of multiple answers print any one of them.
Examples:
Input :Â
Â
Output : 1Â
Vertex 1 is connected to all other non selected vertices. HereÂ
{1, 2}, {2, 3}, {3, 4}, {1, 3}, {1, 4}, {2, 4} are also the valid answersInput :Â
Â
Output : 1 3Â
Vertex 1, 3 are connected to all other non selected vertices. {2, 4} is also a valid answer.Â
Â
Efficient Approach: An efficient way is to find vertices which are even level and odd level using simple dfs or bfs function. Then if the vertices at odd level are less than the vertices at even level then print odd level vertices. Otherwise, print even level vertices.
Below is the implementation of the above approach:Â Â
C++
// C++ program to find K vertices in // the graph which are connected to at // least one of remaining vertices#include <bits/stdc++.h>using namespace std;#define N 200005Â
// To store graphint n, m, vis[N];vector<int> gr[N];vector<int> v[2];Â
// Function to add edgevoid add_edges(int x, int y){Â Â Â Â gr[x].push_back(y);Â Â Â Â gr[y].push_back(x);}Â
// Function to find level of each nodevoid dfs(int x, int state){    // Push the vertex in respected level    v[state].push_back(x);Â
    // Make vertex visited    vis[x] = 1;Â
    // Traverse for all it's child nodes    for (auto i : gr[x])        if (vis[i] == 0)            dfs(i, state ^ 1);}Â
// Function to print verticesvoid Print_vertices(){    // If odd level vertices are less    if (v[0].size() < v[1].size()) {        for (auto i : v[0])            cout << i << " ";    }    // If even level vertices are less    else {        for (auto i : v[1])            cout << i << " ";    }}Â
// Driver codeint main(){Â Â Â Â int n = 4, m = 3;Â
    // Add edges    add_edges(1, 2);    add_edges(2, 3);    add_edges(3, 4);Â
    // Function call    dfs(1, 0);Â
    Print_vertices();Â
    return 0;} |
Java
// Java program to find K vertices in // the graph which are connected to at // least one of remaining verticesimport java.util.*;Â
class GFG{Â
    static final int N = 200005;Â
    // To store graph    static int n, m;    static int[] vis = new int[N];    static Vector<Integer>[] gr = new Vector[N];    static Vector<Integer>[] v = new Vector[2];Â
    // Function to add edge    static void add_edges(int x, int y)     {        gr[x].add(y);        gr[y].add(x);    }Â
    // Function to find level of each node    static void dfs(int x, int state)     {        // Push the vertex in respected level        v[state].add(x);Â
        // Make vertex visited        vis[x] = 1;Â
        // Traverse for all it's child nodes        for (int i : gr[x])        {            if (vis[i] == 0)            {                dfs(i, state ^ 1);            }        }    }Â
    // Function to print vertices    static void Print_vertices()     {        // If odd level vertices are less        if (v[0].size() < v[1].size())         {            for (int i : v[0])             {                System.out.print(i + " ");            }        }                  // If even level vertices are less        else        {            for (int i : v[1])             {                System.out.print(i + " ");            }        }    }Â
    // Driver code    public static void main(String[] args)    {        n = 4;        m = 3;        for (int i = 0; i < N; i++)        {            gr[i] = new Vector<Integer>();        }        for (int i = 0; i < 2; i++)         {            v[i] = new Vector<Integer>();        }                 // Add edges        add_edges(1, 2);        add_edges(2, 3);        add_edges(3, 4);Â
        // Function call        dfs(1, 0);Â
        Print_vertices();    }}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program to find K vertices in# the graph which are connected to at# least one of remaining verticesÂ
N = 200005Â
# To store graphn, m, =0,0vis=[0 for i in range(N)]gr=[[] for i in range(N)]v=[[] for i in range(2)]Â
# Function to add edgedef add_edges(x, y):Â Â Â Â gr[x].append(y)Â Â Â Â gr[y].append(x)Â
# Function to find level of each nodedef dfs(x, state):Â
    # Push the vertex in respected level    v[state].append(x)Â
    # Make vertex visited    vis[x] = 1Â
    # Traverse for all it's child nodes    for i in gr[x]:        if (vis[i] == 0):            dfs(i, state ^ 1)Â
Â
# Function to prverticesdef Print_vertices():Â
    # If odd level vertices are less    if (len(v[0]) < len(v[1])):        for i in v[0]:            print(i,end=" ")    # If even level vertices are less    else:        for i in v[1]:            print(i,end=" ")Â
# Driver codeÂ
n = 4m = 3Â
# Add edgesadd_edges(1, 2)add_edges(2, 3)add_edges(3, 4)Â
# Function calldfs(1, 0)Â
Print_vertices()Â
# This code is contributed by mohit kumar 29 |
C#
    // C# program to find K vertices in // the graph which are connected to at // least one of remaining verticesusing System;using System.Collections.Generic;Â
class GFG{Â Â Â Â static readonly int N = 200005;Â
    // To store graph    static int n, m;    static int[] vis = new int[N];    static List<int>[] gr = new List<int>[N];    static List<int>[] v = new List<int>[2];Â
    // Function to add edge    static void add_edges(int x, int y)     {        gr[x].Add(y);        gr[y].Add(x);    }Â
    // Function to find level of each node    static void dfs(int x, int state)     {        // Push the vertex in respected level        v[state].Add(x);Â
        // Make vertex visited        vis[x] = 1;Â
        // Traverse for all it's child nodes        foreach (int i in gr[x])        {            if (vis[i] == 0)            {                dfs(i, state ^ 1);            }        }    }Â
    // Function to print vertices    static void Print_vertices()     {        // If odd level vertices are less        if (v[0].Count < v[1].Count)         {            foreach (int i in v[0])             {                Console.Write(i + " ");            }        }                  // If even level vertices are less        else        {            foreach (int i in v[1])             {                Console.Write(i + " ");            }        }    }Â
    // Driver code    public static void Main(String[] args)    {        n = 4;        m = 3;        for (int i = 0; i < N; i++)        {            gr[i] = new List<int>();        }        for (int i = 0; i < 2; i++)         {            v[i] = new List<int>();        }                 // Add edges        add_edges(1, 2);        add_edges(2, 3);        add_edges(3, 4);Â
        // Function call        dfs(1, 0);Â
        Print_vertices();    }}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript program to find K vertices in // the graph which are connected to at // least one of remaining verticeslet N = 200005;Â
// To store graphlet n, m;let vis = new Array(N);for(let i = 0; i < N; i++){Â Â Â Â vis[i] = 0;}Â
let gr = new Array(N);let v = new Array(2);Â
// Function to add edgefunction add_edges(x, y){Â Â Â Â gr[x].push(y);Â Â Â Â gr[y].push(x);}Â
// Function to find level of each node   function dfs(x, state){         // Push the vertex in respected level    v[state].push(x);Â
    // Make vertex visited    vis[x] = 1;Â
    // Traverse for all it's child nodes    for(let i = 0; i < gr[x].length; i++)    {        if (vis[gr[x][i]] == 0)        {            dfs(gr[x][i], (state ^ 1));        }    }}Â
// Function to print verticesfunction Print_vertices() {         // If odd level vertices are less    if (v[0].length < v[1].length)     {        for(let i = 0; i < v[0].length; i++)         {            document.write(v[0][i] + " ");        }    }           // If even level vertices are less    else    {        for(let i = 0; i < v[1].length; i++)         {            document.write(v[1][i] + " ");        }    }}Â
// Driver coden = 4;m = 3;for(let i = 0; i < N; i++){Â Â Â Â gr[i] = [];}for(let i = 0; i < 2; i++) {Â Â Â Â v[i] = [];}Â Â Â // Add edgesadd_edges(1, 2);add_edges(2, 3);add_edges(3, 4);Â
// Function calldfs(1, 0);Â Â Â Print_vertices();Â
// This code is contributed by unknown2108Â
</script> |
PHP
<?php// PHP program to find K vertices in// the graph which are connected to at// least one of remaining verticesÂ
class GFG {Â Â Â Â Â Â Â Â Â const N = 200005;Â
    // To store graph    public $n, $m;    public $vis = array();    public $gr = array();    public $v = array();Â
    public function __construct() {        for ($i = 0; $i < self::N; $i++) {            $this->gr[$i] = array();        }        for ($i = 0; $i < 2; $i++) {            $this->v[$i] = array();        }    }Â
    // Function to add edge    public function add_edges($x, $y) {        array_push($this->gr[$x], $y);        array_push($this->gr[$y], $x);    }Â
    // Function to find level of each node    public function dfs($x, $state) {        // Push the vertex in respected level        array_push($this->v[$state], $x);Â
        // Make vertex visited        $this->vis[$x] = 1;Â
        // Traverse for all it's child nodes        foreach ($this->gr[$x] as $i) {            if ($this->vis[$i] == 0) {                $this->dfs($i, $state ^ 1);            }        }    }Â
    // Function to print vertices    public function Print_vertices() {        // If odd level vertices are less        if (count($this->v[0]) < count($this->v[1])) {            foreach ($this->v[0] as $i) {                echo $i . " ";            }        }        // If even level vertices are less        else {            foreach ($this->v[1] as $i) {                echo $i . " ";            }        }    }Â
    // Driver code    public function main() {        $this->n = 4;        $this->m = 3;Â
        // Add edges        $this->add_edges(1, 2);        $this->add_edges(2, 3);        $this->add_edges(3, 4);Â
        // Function call        $this->dfs(1, 0);Â
        $this->Print_vertices();    }}Â
$gfg = new GFG();$gfg->main();Â
// This code is contributed by rajsanghavi9?> |
2 4
Â
Time Complexity : O(V+E)Â
Where V is the number of vertices and E is the number of edges in the graph.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

