📜  图中要着色的最小节点,以便每个节点都有一个已着色的邻居

📅  最后修改于: 2021-05-06 20:07:12             🧑  作者: Mango

给定一个具有V个节点和E个边缘的图形G ,任务是对不超过floor(V / 2)个节点进行着色,以使每个节点在至少1个单位的距离处至少具有一个着色节点。图的任何两个连接节点之间的距离始终正好为1个单位。打印需要着色的节点。

例子:

方法:可以使用BFS遍历解决此问题。请按照以下步骤解决问题:

  • 初始化数组奇数[]偶数[]以存储与源分别处于奇数和偶数个节点距离的节点。
  • 从源节点开始,执行BFS遍历,并将距离初始化为0,该距离表示距源节点的距离。根据distance的值将所有节点存储在特定级别的奇数[]或偶数[]中。
  • 如果distance为奇数,即(distance&1)为1,则将该节点插入奇数[]。否则,插入even []。
  • 现在,使用最少的元素打印数组中的节点。
  • 由于奇数距离或偶数距离的节点数中的最小值不超过floor(V / 2) ,因此答案保持正确,因为奇数距离的每个节点都连接到偶数距离的节点,反之亦然。
  • 因此,如果到源的偶数距离处的节点数较少,则从even []中打印节点。否则,从奇数[]中打印所有节点。

下面是上述方法的实现:

C++
// C++ Program to implement the
// above approach
 
#include 
using namespace std;
 
// Stores the graph
map > graph;
 
// Stores the visited nodes
map vis;
 
// Stores the nodes
// at odd distance
vector odd;
 
// Stores the nodes at
// even distance
vector even;
 
// Function to seperate and
// store the odd and even
// distant nodes from source
void bfs()
{
    // Source node
    int src = 1;
 
    // Stores the nodes and their
    // respective distances from
    // the source
    queue > q;
 
    // Insert the source
    q.push({ src, 0 });
 
    // Mark the source visited
    vis[src] = 1;
 
    while (!q.empty()) {
 
        // Extract a node from the
        // front of the queue
        int node = q.front().first;
        int dist = q.front().second;
        q.pop();
 
        // If distance from source
        // is odd
        if (dist & 1) {
            odd.push_back(node);
        }
 
        // Otherwise
        else {
            even.push_back(node);
        }
 
        // Traverse its neighbors
        for (auto i : graph[node]) {
 
            // Insert its unvisited
            // neighbours into the queue
            if (!vis.count(i)) {
 
                q.push({ i, (dist + 1) });
                vis[i] = 1;
            }
        }
    }
}
 
// Driver Program
int main()
{
    graph[1].push_back(2);
    graph[2].push_back(1);
    graph[2].push_back(3);
    graph[3].push_back(2);
    graph[3].push_back(4);
    graph[4].push_back(3);
    graph[4].push_back(5);
    graph[5].push_back(4);
    graph[5].push_back(6);
    graph[6].push_back(5);
    graph[6].push_back(1);
    graph[1].push_back(6);
 
    bfs();
 
    if (odd.size() < even.size()) {
        for (int i : odd) {
            cout << i << " ";
        }
    }
    else {
        for (int i : even) {
            cout << i << " ";
        }
    }
    return 0;
}


Java
// Java program to implement the
// above approach
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
 
class Pair
{
    int first, second;
 
    public Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
class GFG{
 
// Stores the graph
static Map> graph = new HashMap<>();
 
// Stores the visited nodes
static Map vis = new HashMap<>();
 
// Stores the nodes
// at odd distance
static ArrayList odd = new ArrayList<>();
 
// Stores the nodes at
// even distance
static ArrayList even = new ArrayList<>();
 
// Function to seperate and
// store the odd and even
// distant nodes from source
static void bfs()
{
     
    // Source node
    int src = 1;
 
    // Stores the nodes and their
    // respective distances from
    // the source
    Queue q = new LinkedList<>();
 
    // Insert the source
    q.add(new Pair(src, 0));
 
    // Mark the source visited
    vis.put(src, 1);
 
    while (!q.isEmpty())
    {
         
        // Extract a node from the
        // front of the queue
        int node = q.peek().first;
        int dist = q.peek().second;
        q.poll();
 
        // If distance from source
        // is odd
        if ((dist & 1) != 0)
        {
            odd.add(node);
        }
 
        // Otherwise
        else
        {
            even.add(node);
        }
 
        // Traverse its neighbors
        for(Integer i : graph.get(node))
        {
             
            // Insert its unvisited
            // neighbours into the queue
            if (!vis.containsKey(i))
            {
                q.add(new Pair(i, (dist + 1)));
                vis.put(i, 1);
            }
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    graph.put(1, new ArrayList<>());
    graph.put(2, new ArrayList<>());
    graph.put(3, new ArrayList<>());
    graph.put(4, new ArrayList<>());
    graph.put(5, new ArrayList<>());
    graph.put(6, new ArrayList<>());
    graph.get(1).add(2);
    graph.get(2).add(1);
    graph.get(2).add(3);
    graph.get(3).add(2);
    graph.get(3).add(4);
    graph.get(4).add(3);
    graph.get(4).add(5);
    graph.get(5).add(4);
    graph.get(5).add(6);
    graph.get(6).add(5);
    graph.get(6).add(1);
    graph.get(1).add(6);
 
    bfs();
 
    if (odd.size() < even.size())
    {
        for(int i : odd)
        {
            System.out.print(i + " ");
        }
    }
    else
    {
        for(int i : even)
        {
            System.out.print(i + " ");
        }
    }
}
}
 
// This code is contributed by sanjeev2552


Python3
# Python3 Program to implement the
# above approach
  
# Stores the graph
graph = dict()
  
# Stores the visited nodes
vis = dict()
  
# Stores the nodes
# at odd distance
odd = []
  
# Stores the nodes at
# even distance
even = []
  
# Function to seperate and
# store the odd and even
# distant nodes from source
def bfs():
 
    # Source node
    src = 1;
  
    # Stores the nodes and their
    # respective distances from
    # the source
    q = []
  
    # Insert the source
    q.append([ src, 0 ]);
  
    # Mark the source visited
    vis[src] = 1;
  
    while (len(q) != 0):
  
        # Extract a node from the
        # front of the queue
        node = q[0][0]
        dist = q[0][1]
        q.pop(0);
  
        # If distance from source
        # is odd
        if (dist & 1):
            odd.append(node);
  
        # Otherwise
        else:
            even.append(node);
          
        # Traverse its neighbors
        for i in graph[node]:
  
            # Insert its unvisited
            # neighbours into the queue
            if (i not in vis):
  
                q.append([ i, (dist + 1) ]);
                vis[i] = 1;
              
# Driver code
if __name__=='__main__':
 
    graph[1] = [2, 6]
    graph[2] = [1, 3]
    graph[3] = [2, 4]
    graph[4] = [3, 5]
    graph[5] = [4, 6]
    graph[6] = [5, 1]
  
    bfs();
  
    if (len(odd) < len(even)):
        for i in odd:
            print(i, end = ' ')
             
    else:
        for i in even:
            print(i, end = ' ')
             
# This code is contributed by rutvik_56


输出:
1 3 5

时间复杂度: O(V + E)