我正在研究迷宫解决方案的问题。在代码找到目标后,我不能让python打印出一个解决方案列表。但这是家庭作业所必需的。
有人能帮助我吗?我刚刚学习了3周的python。我想打印出python走向最终目标的每一步。这是我的代码:
def mazeDetector(row,col):
c= m[row][col]
solution=[]
if c =="W":
print "Wall here: "+ str(row)+ ","+ str(col)
return False
elif c =="V":
print "Visited: " + str(row)+ ","+ str(col)
return False
elif c=="F":
print "Found: "+ str(row)+ ","+ str(col)
print solution
return True
print "visiting:"+ str(row)+ ","+ str(col)
solution.append((row,col),)
m[row][col]=="V"
if (col>0 and mazeDetector(row,col-1)):
return True
elif (row< len(m)-1 and mazeDetector(row+1,col)):
return True
elif (row>0 and mazeDetector(row-1, col)):
return True
elif (col<=len(m)-1 and mazeDetector(row, col+1)):
return True
return False
mazeDetector(1,5)
这是迷宫,W
表示墙,P
表示去处,S
表示开始,F
表示最终:
[['W', 'P', 'P', 'W', 'W', 'W'],
['W', 'W', 'P', 'W', 'P', 'S'],
['W', 'W', 'P', 'W', 'P', 'W'],
['P', 'P', 'P', 'P', 'P', 'W'],
['F', 'W', 'P', 'W', 'W', 'W'],
['W', 'P', 'P', 'P', 'P', 'W']]
答案 0 :(得分:1)
你必须将解决方案传递给你的函数,而不是每次都创建它:
def mazeDetector(row,col, solution):
c= m[row][col]
solution.append((row, col))
if c =="W":
print "Wall here: "+ str(row)+ ","+ str(col)
return False
elif c =="V":
print "Visited: " + str(row)+ ","+ str(col)
return False
elif c=="F":
print "Found: "+ str(row)+ ","+ str(col)
print solution
return True
print "visiting:"+ str(row)+ ","+ str(col)
m[row][col]=="V"
if (col>0 and mazeDetector(row,col-1, list(solution))):
return True
elif (row< len(m)-1 and mazeDetector(row+1,col, list(solution))):
return True
elif (row>0 and mazeDetector(row-1, col, list(solution))):
return True
elif (col<=len(m)-1 and mazeDetector(row, col+1, list(solution))):
return True
return False
mazeDetector(1,5, [])
这里的代码返回路径(如果存在)
def mazeDetector(row, col, solution):
solution.append((row, col))
if m[row][col] == "F": return True, solution
m[row][col] = "V"
neighbors = [(row, col - 1), (row + 1, col), (row - 1, col), (row, col + 1)]
neighbors = filter(lambda (r, c): r >= 0 and c >= 0 and r < len(m) and c < len(m) and m[r][c] not in ("V", "W"), neighbors)
for r, c in neighbors:
t, sol = mazeDetector(r, c, list(solution))
if t: return True, sol
return False, []
print mazeDetector(1, 5, [])[1]
答案 1 :(得分:0)
你可以简单地用你想要的另一个符号'g'替换你实际解决的路线上的'P'!这就是这样!