【发布时间】:2020-12-15 02:53:45
【问题描述】:
考虑下面的代码。假设所讨论的图有 N 个节点,每个节点最多有 D 个邻居,并且 D+1 种颜色可用于为节点着色,这样与一条边相连的两个节点都不会分配给它们相同的颜色。我认为下面代码的复杂性是 O(N*D),因为对于 N 个节点中的每一个,我们循环遍历该节点的最多 D 个邻居以填充集合非法颜色,然后遍历包含 D+1 的颜色列表颜色。但是给出的复杂度是 O(N+M),其中 M 是边数。我在这里做错了什么?
def color_graph(graph, colors):
for node in graph:
if node in node.neighbors:
raise Exception('Legal coloring impossible for node with loop: %s' %
node.label)
# Get the node's neighbors' colors, as a set so we
# can check if a color is illegal in constant time
illegal_colors = set([
neighbor.color
for neighbor in node.neighbors
if neighbor.color
])
# Assign the first legal color
for color in colors:
if color not in illegal_colors:
node.color = color
break
【问题讨论】:
标签: python graph graph-coloring