为图着色问题创建特定的节点顺序

时间:2019-03-25 14:16:13

标签: python networkx graph-theory graph-coloring

我在算法上苦苦挣扎,无法为图形上色。 让我们考虑下图:

Network graph

import networkx as nx
from matplotlib import pyplot as plt

nodes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
edges = [(1, 2), (2, 3), (3, 4), (4, 5), (1, 5), (5, 6), (6, 10), 
         (6, 7), (4, 7), (3, 8), (7, 8), (8, 9), (8, 11)]

# Create the graph
G = nx.Graph()
# Add edges
G.add_edges_from(edges)
# Plot
nx.draw(G, with_labels=True, font_size = 16)
plt.show()

我希望有多个起点,称为initial_nodes,并在相邻节点周围创建订单。对于上图,让我们将起始节点视为节点27

顺序为:

# Step 1: - Initial nodes
order = [2, 7]
# Step 2: - Nodes adjacent to the initial nodes
order = [2, 7, 1, 3, 4, 6, 8]
# Step 3: - Nodes adjacent to the nodes added in the previous step
# If they are not already present in the order...
order = [2, 7, 1, 3, 4, 6, 8, 5, 10, 9, 11]

我觉得递归方法应该很好用,但是我不知道如何写下来。有想法吗?

编辑:所有问题都描述为further

当前创建订单的算法:

def create_node_order(graph, initial_nodes):
    """
    Create the node order.
    """
    # Initialization
    order = initial_nodes
    next_nodes = list()

    for node in initial_nodes:
        for adj_node in graph.adj[node].keys():
            if adj_node not in order:
                order.append(adj_node)
                next_nodes.append(adj_node)

    while len(next_nodes) != 0:

        for node in next_nodes:
            for adj_node in graph.adj[node].keys():
                if adj_node not in order:
                    order.append(adj_node)
                    next_nodes.append(adj_node)

            next_nodes.remove(node)

    return order

1 个答案:

答案 0 :(得分:1)

请注意,考虑到从某些起始节点迭代“圆”“辐射”的方法,并不是导致最佳着色的必要条件,甚至被证明是不可能的。鉴于我对所描述的算法及其要求有一定的了解,因此我将使用以下内容:

伪代码:

// no need for more than four colors IFF the algorithm is optimal and the graph is planar, otherwise extend
colors = [red, blue, green, yellow]
// initialize
graph = SomeSuitableDataStructure(data)
queue = [graph(2), graph(7)] // starting nodes
for node in graph.nodes:
    node.visited = False
    node.color = Undefined

while not queue.empty():
    node = queue.pop()
    node.visited = True
    node.color = first_color_not_in([n.color for n in node.neighbors()])
    for neighbor in node.neighbors():
        if not neighbor.visited: queue.push_back(neighbor)

实施first_color_not_in()和处理Undefined颜色作为练习的重点。