python-3.x - 使用 BFS 和 IDFS 进行地图着色 - Python 3
问题描述
我正在尝试使用深度优先搜索、广度优先搜索和 IDFS 算法来解决地图着色问题(使用 Python 3)。下面是我试图修改的代码(它给出了回溯的结果)。任何人都可以看看并帮助:
这段代码给出了回溯的结果。我无法修改代码,因此它使用 BFS 和 IDFS 搜索节点。import collections
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
def check_valid(graph):
for node,nexts in graph.items():
assert(nexts) # no isolated node
assert(node not in nexts) ####### no node linked to itself
for next in nexts:
assert(next in graph and node in graph[next]) ####### A linked to B implies B linked to A
class MapColor:
def __init__(self, graph, colors):
check_valid(graph)
self.graph = graph
nodes = list(self.graph.keys())
self.node_colors = { node: None for node in nodes }
self.domains = { node: set(colors) for node in nodes }
def solve(self):
bfs(map,'R1')
uncolored_nodes = [n for n,c in self.node_colors.items() if c is None]
if not uncolored_nodes:
print (self.node_colors)
return True
node = uncolored_nodes[0]
print ('domain for ' + node + ': ' + str(self.domains[node]))
for color in self.domains[node]:
if all(color != self.node_colors[n] for n in self.graph[node]):
self.set_color(node, color)
self.remove_from_domains(node, color)
if self.solve():
return True
self.set_color(node, None)
self.add_to_domains(node, color)
return False
def set_color(self, key, color):
self.node_colors[key] = color
def remove_from_domains(self, key, color):
for node in self.graph[key]:
if color in self.domains[node]:
self.domains[node].remove(color)
def add_to_domains(self, key, color):
for node in self.graph[key]:
self.domains[node].add(color)
colors = {'green', 'red', 'blue'}
map={"R1":["R2","R3"],
"R2":["R1","R3","R4"],
"R3":["R1","R2","R4"],
"R4":["R2","R3"]
}
problem = MapColor(map, colors)
problem.solve()
解决方案
推荐阅读
- algorithm - 如何设计一个动态规划算法来找到两个序列之间的最长公共子序列?
- nginx - Kubernetes:具有共享服务的复制有状态 nginx 负载均衡器
- javascript - 获取值失败
- javascript - 将查询字符串附加到 div 点击上的链接目标 url
- python - 如何使用卷积神经网络启动我的模型
- javascript - 从另一个 .js 文件访问实例属性
- asynchronous - 如何返回一个返回 Rust 特征的函数
- c++ - Qt QML 点击下边界框
- java - 在 Piccolo2d 中禁用选定对象的拖动?
- python - 如何对图像执行像素归一化