问题描述
类迷宫: def init (自我,迷宫): self.maze =迷宫
def isSafe(self,maze,x,y,visited):
# Get Maze dimensions (N x M) rather than hardcoding using N as a global
N = len(maze)
M = len(maze[0])
# x,y safe to use if not visited (original code had visited)
# if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1 and visited[x][y] == True:
# Can simplify x >= 0 and x < N to 0 <= x < M
return 0 <= x < N and 0 <= y < M and self.maze[x][y] == 1 and not visited[x][y]
def maze_solver(self,maze):
# Get Maze dimensions (N x M) rather than hardcoding using N as a global
N = len(self.maze)
M = len(self.maze[0])
sol = [[0 for j in range(M)] for i in range(N)]
visited = [[0 for j in range(M)] for i in range(N)]
if not self.dfs(maze,sol,visited): # preferred to checking for False
print("Solution doesn't exist")
print(-1)
return False
printSolution(sol)
return True
def dfs(self,visited):
# Get Maze dimensions (N x M) as row and column
N = len(self.maze)
M = len(self.maze[0])
if x == N - 1 and y == M - 1 and maze[x][y] == 1:
sol[x][y] = 1
return True
if self.isSafe(maze,visited): # preferred to checking for True
sol[x][y] = 1 # Try solution from current x,y position
# Mark as visited so no other soltuion will use it
visited[x][y] = True
# Recursive calls to dfs() can be simplfied to the following:
if (self.dfs(maze,x + 1,visited) or
self.dfs(maze,y - 1,x - 1,visited) or
self.dfs(maze,y + 1,visited)):
return True # Found a solution
else:
sol[x][y] = 0 # Couldn't use x,y in solution
return False
else:
return False
def printSolution(sol):
for i in sol:
for j in i:
print(str(j) + " ",end="")
print("")
如果名称 ==“ 主要”: maze1 = Maze()
print("\nTest 1")
maze = [[1,0],[1,1,1],[0,1]]
maze1.maze_solver(maze)
我想使用oops概念运行该程序。但是,即时通讯卡住了,没有得到输出。如果我不使用oops概念,那么输出是正确的,但是我想知道我将如何实现
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)