我是python和计算的新手。这是我要使用Python实现的问题:三对夫妇要从东到西过一条河。在那儿找到的船只能坐两个人。如果妻子没有丈夫就不能和其他男人住在一起,该如何渡河?
首先,我创建了所有可能的状态。
def genStates():
"""
A function to generate all the possible states.
Input: None
Output: all the possible states
"""
states = []
side = ("E","W")
for a in side:
for b in side:
for c in side:
for d in side:
for e in side:
for f in side:
z = a+b+c+d+e+f
states.append(z)
return states
然后,我创建了一个图表来放置合法状态及其可能的动作。
def genGraph(S):
"""
A function to generate a graph that contains all the legal states and their next possible states to move
Input: All the possible states
Output: A graph of all the legal states and their next possible states to move
"""
G = []
graph = {}
for i in range(len(S)):
if isLegal(S[i]) == True:
G.append(S[i])
for i in range(len(G)):
result1 = nextStates(G[i], G)
graph.update({G[i]: result1[1:]}) # add possible states to each legal states, put it in graph
return graph
我创建了genGraph中使用的两个函数。
def isLegal(S):
"""
A function to check if a state is legal or not.
Input: None
Output: Return True if a state is legal, else return False.
"""
if S[0] != S[1]:
if S[1] == S[2] or S[1] == S[4]:
return False
elif S[2] != S[3]:
if S[3] == S[0] or S[3] == S[4]:
return False
elif S[4] != S[5]:
if S[5] == S[0] or S[5] == S[2]:
return False
return True
和
def nextStates(startnode, allstates):
"""
A function to return a set of states that a state can move to.
Input: A state and all the possible states
Output: a set of states that a state can move to
"""
possible = [startnode]
count1 = startnode.count("E")
count2 = startnode.count("W")
for i in range(1, len(allstates)):
if allstates[i].count("E") - count1 <= 2 and allstates[i].count("E") - count1 >= -2 and allstates[i].count(
"W") - count2 <= 2 and allstates[i].count("W") - count2 >= -2:
count = 0
for j in range(0,len(startnode)):
if allstates[i][j] == startnode[j]:
count += 1
if count >= 4: # Unlike MCGW problem, single unit's journey is unnecessary
possible.append(allstates[i])
return possible
最后,我使用python网站上的函数来获取实现此问题的最短路径。
def genShortestPath(graph, start, end, path=[]):
"""
A function to find the shortest path in a graph, from the start to the destination.
Input: A graph of all the legal states and their states next possible states to move, the starting point and the destination
Output: the shortest path of the graph
"""
path = path + [start]
if start == end:
return path
if not (start in graph):
return None
shortestPath = None
for node in graph[start]:
if node not in path:
newpath = genShortestPath(graph, node, end, path)
if newpath:
if not shortestPath or len(newpath) < len(shortestPath):
shortestPath = newpath
return shortestPath
最后,当我实现此问题时,由于某些原因,它找不到最短的解决方案。我打印出图表,然后使用下一个状态函数检查这些代码是否存在任何问题,但是运行良好。这里有什么问题?这是实现代码:
def Solver():
S = genStates()
G = genGraph(S)
s = "EEEEEE" # source node
d = "WWWWWW" # destination node
result = genShortestPath(G, s, d)
print(result)