我正在使用NetworkX Python库。我要解决的问题的更广泛描述是here。
我想同时找到1)至少访问每个节点一次的有效路径 和2)基于边缘权重访问的最短路径每个节点至少一次。
这听起来像是旅行商问题的变体。值得注意的另一件事是,该图几乎是 无向的-大多数节点是双向连接的,只有少数几个(<所有节点的20%)是单向连接的。
我查看了NetworkX算法,但似乎没有一个满足这个问题。
用于生成图形的代码为:
def generate_graph(self):
ind = (12, 0)
self.ball = ind
locs = [ind]
while len(locs):
next_loc = locs.pop()
if not self.nodes[next_loc]:
self.nodes[next_loc] = AmazeGameLocation(next_loc)
self.paths.add_node(self.nodes[next_loc])
moves = [("U", (-1, 0)), ("D", (1, 0)), ("L", (0, -1)), ("R", (0, 1))]
for move in moves:
next_move_loc = add_tuples(move[1], next_loc)
if self.is_move_possible(next_move_loc):
next_attempt = add_tuples(move[1], next_move_loc)
weight = 1
while self.is_move_possible(next_attempt):
next_move_loc = next_attempt
next_attempt = add_tuples(move[1], next_move_loc)
weight += 1
if not self.nodes[next_move_loc]:
self.nodes[next_move_loc] = AmazeGameLocation(next_move_loc)
self.paths.add_node(self.nodes[next_move_loc])
locs.append(next_move_loc)
self.paths.add_edge(self.nodes[next_loc], self.nodes[next_move_loc], weight=weight)
self.nodes[next_loc].dirs[move[0]] = self.nodes[next_move_loc]
示例图为here。
有关此图和问题的更多信息,请访问我的GitHub here。
答案 0 :(得分:0)
我想找到以下两种情况:1)至少访问每个节点一次的有效路径,以及2)基于边缘权重的最少访问每个节点一次的最短路径。
对于1):非常简单,您可以尝试查找例如图表的spanning tree。然后,您可以遍历此生成树来构建访问图形中所有顶点的路径。
对于2):假设G
为图,则可以构建G'
的“度量完成度”,即G
的顶点为G'
的顶点,并且对于G
的任意两个顶点,u, v
中都有一条边u,v
,权重为从G'
开始的最短路径的权重到u
中的v
。
然后,您要做的就是在G
上解决TSP,以获得在G'
上寻找的解决方案。