数据结构迷宫栈完整代码
时间: 2023-11-16 11:06:04 浏览: 88
好的,以下是数据结构迷宫栈的完整代码:
```python
class Maze:
def __init__(self, maze):
self.maze = maze
self.width = len(maze[0])
self.height = len(maze)
self.start = None
self.end = None
def find_start_end(self):
for i in range(self.height):
for j in range(self.width):
if self.maze[i][j] == 'S':
self.start = (i, j)
elif self.maze[i][j] == 'E':
self.end = (i, j)
def is_valid_move(self, x, y):
if x < 0 or x >= self.height or y < 0 or y >= self.width:
return False
if self.maze[x][y] == '#':
return False
return True
def get_neighbors(self, x, y):
neighbors = []
if self.is_valid_move(x-1, y):
neighbors.append((x-1, y))
if self.is_valid_move(x+1, y):
neighbors.append((x+1, y))
if self.is_valid_move(x, y-1):
neighbors.append((x, y-1))
if self.is_valid_move(x, y+1):
neighbors.append((x, y+1))
return neighbors
def solve(self):
stack = [(self.start, [self.start])]
visited = set()
while stack:
(x, y), path = stack.pop()
if (x, y) == self.end:
return path
if (x, y) in visited:
continue
visited.add((x, y))
for neighbor in self.get_neighbors(x, y):
stack.append((neighbor, path + [neighbor]))
return None
```
其中,`maze` 是一个二维列表,表示迷宫地图;`start` 和 `end` 分别表示起点和终点的坐标。
阅读全文