📜  无向图中的最大独立集

📅  最后修改于: 2021-09-06 05:46:21             🧑  作者: Mango

给定一个由顶点数V和边E[ ]定义的无向图,任务是在无向图中找到最大独立顶点集。

注意:假设至少有一种方法可以从图中的任何顶点遍历到另一个顶点,即该图具有一个连通分量。

例子:

方法:
这个问题是一个 NP-Hard 问题,只能在指数时间内解决(截至目前)。
请按照以下步骤解决问题:

  • 遍历图的顶点并使用回溯来检查顶点是否可以包含在最大独立集中
  • 每个顶点有两种可能性,是否可以包含在最大独立集中。
  • 最初开始,考虑所有顶点和边。一个接一个,选择一个顶点。从图中移除该顶点,将其从最大独立集 中排除,并递归遍历剩余的图以找到最大独立集。
  • 否则,考虑最大独立集中的选定顶点并从中删除其所有邻居。继续寻找排除其邻居的最大独立集。
  • 对所有顶点重复此过程并打印获得的最大独立集。

下面是上述方法的实现:

Python3
# Python Program to implement
# the above approach
  
# Recursive Function to find the
# Maximal Independent Vertex Set    
def graphSets(graph):
      
    # Base Case - Given Graph 
    # has no nodes
    if(len(graph) == 0):
        return []
     
    # Base Case - Given Graph
    # has 1 node
    if(len(graph) == 1):
        return [list(graph.keys())[0]]
      
    # Select a vertex from the graph
    vCurrent = list(graph.keys())[0]
      
    # Case 1 - Proceed removing
    # the selected vertex
    # from the Maximal Set
    graph2 = dict(graph)
      
    # Delete current vertex 
    # from the Graph
    del graph2[vCurrent]
      
    # Recursive call - Gets 
    # Maximal Set,
    # assuming current Vertex 
    # not selected
    res1 = graphSets(graph2)
      
    # Case 2 - Proceed considering
    # the selected vertex as part
    # of the Maximal Set
  
    # Loop through its neighbours
    for v in graph[vCurrent]:
          
        # Delete neighbor from 
        # the current subgraph
        if(v in graph2):
            del graph2[v]
      
    # This result set contains VFirst,
    # and the result of recursive
    # call assuming neighbors of vFirst
    # are not selected
    res2 = [vCurrent] + graphSets(graph2)
      
    # Our final result is the one 
    # which is bigger, return it
    if(len(res1) > len(res2)):
        return res1
    return res2
  
# Driver Code
V = 8
  
# Defines edges
E = [ (1, 2),
      (1, 3),
      (2, 4),
      (5, 6),
      (6, 7),
      (4, 8)]
  
graph = dict([])
  
# Constructs Graph as a dictionary 
# of the following format-
  
# graph[VertexNumber V] 
# = list[Neighbors of Vertex V]
for i in range(len(E)):
    v1, v2 = E[i]
      
    if(v1 not in graph):
        graph[v1] = []
    if(v2 not in graph):
        graph[v2] = []
      
    graph[v1].append(v2)
    graph[v2].append(v1)
  
# Recursive call considering 
# all vertices in the maximum 
# independent set
maximalIndependentSet = graphSets(graph)
  
# Prints the Result 
for i in maximalIndependentSet:
    print(i, end =" ")


输出:
2 3 8 5 7

时间复杂度: O(2 N )
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live