Python迷宫问题求解代码
时间: 2024-01-21 07:44:35 浏览: 73
Sure, 我可以为您提供一个 Python 迷宫求解器代码。该代码使用了深度优先搜索算法来解决迷宫问题。
```python
def maze_solver(maze, start, end):
maze_rows = len(maze)
maze_cols = len(maze[0])
solution_grid = [[0 for j in range(maze_cols)] for i in range(maze_rows)]
# Check if start and end points are obstacles
if maze[start[0]][start[1]] == 1 or maze[end[0]][end[1]] == 1:
return "No Solution!"
# Mark the starting cell in the solution grid
solution_grid[start[0]][start[1]] = 1
# Define potential move directions - left, right, up, down
move_directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
# Recursive function to check for possible paths
def solve_maze(curr_row, curr_col):
# Check if the current position is the end cell
if curr_row == end[0] and curr_col == end[1]:
solution_grid[curr_row][curr_col] = 1
return True
# Check all directions for a possible path
for direction in move_directions:
new_row = curr_row + direction[0]
new_col = curr_col + direction[1]
if (new_row >= 0 and new_row < maze_rows and
new_col >= 0 and new_col < maze_cols and
maze[new_row][new_col] == 0 and
solution_grid[new_row][new_col] == 0):
solution_grid[new_row][new_col] = 1
if solve_maze(new_row, new_col):
return True
# Backtracking
solution_grid[new_row][new_col] = 0
return False
if solve_maze(start[0], start[1]):
return solution_grid
else:
return "No Solution!"
```
请注意,这只是一个简单的例子实现,您可能需要进行一些修改,以使其适用于您的问题。
阅读全文