问题描述
我有一个随机无向图生成器和一个旅行推销员问题的代码,但我不知道如何将它们组合在一起工作,因为旅行推销员问题现在适用于一个非常小的图,我需要它与一个更大的。
import networkx as nx
from itertools import combinations
from random import random
def ER(n,p):
V = set([v for v in range(n)])
E = set()
for combination in combinations(V,2):
a = random()
if a < p:
E.add(combination)
g = nx.Graph()
g.add_nodes_from(V)
g.add_edges_from(E)
return g
n = 10
p = 0.4
g1 = ER(n,p)
pos = nx.spring_layout(g1)
nx.draw_networkx(g1,pos)
plt.title("Random Graph Generation Example")
plt.show()
这是旅行商问题代码:
def __init__(self,vertices):
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
self.V = vertices
''' Check if this vertex is an adjacent vertex
of the prevIoUsly added vertex and is not
included in the path earlier '''
def isSafe(self,v,pos,path):
# Check if current vertex and last vertex
# in path are adjacent
if self.graph[ path[pos-1] ][v] == 0:
return False
# Check if current vertex not already in path
for vertex in path:
if vertex == v:
return False
return True
# A recursive utility function to solve
# hamiltonian cycle problem
def hamCycleUtil(self,path,pos):
# base case: if all vertices are
# included in the path
if pos == self.V:
# Last vertex must be adjacent to the
# first vertex in path to make a cyle
if self.graph[ path[pos-1] ][ path[0] ] == 1:
return True
else:
return False
# Try different vertices as a next candidate
# in Hamiltonian Cycle. We don't try for 0 as
# we included 0 as starting point in hamCycle()
for v in range(1,self.V):
if self.isSafe(v,path) == True:
path[pos] = v
if self.hamCycleUtil(path,pos+1) == True:
return True
# Remove current vertex if it doesn't
# lead to a solution
path[pos] = -1
return False
def hamCycle(self):
path = [-1] * self.V
path[0] = 0
if self.hamCycleUtil(path,1) == False:
print ("Solution does not exist\n")
return False
self.printSolution(path)
return True
def printSolution(self,path):
print ("Solution Exists: Following","is one Hamiltonian Cycle")
for vertex in path:
print (vertex,end = " ")
print (path[0],"\n")
# Driver Code
''' Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) '''
g1 = Graph(5)
g1.graph = [ [0,1,0],[1,1],[0,],]
# Print the solution
g1.hamCycle();
任何帮助将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)