逆向走迷宫脚本
逆向走迷宫脚本
呜哇
import re
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
directions = ["w", "s", "a", "d"]
# 分别对应x坐标的wsad
def map_input(lenx):
mapray = []
n = 0
output_string = re.sub(r',', ' ', input("请输入地图数据,以逗号分隔: "))
maplist = output_string.split()
for i in range(len(maplist)):
if n % lenx == 0:
mapray.append([])
mapray[-1].append(int(maplist[i]))
n += 1
return mapray
def dfs(x, y, mapray, visited, rx, ry, path):
if mapray[y][x] == 1 or visited[y][x]:
return False
visited[y][x] = True
if x == rx and y == ry:
return True
for i in range(4):
new_x = x + dx[i]
new_y = y + dy[i]
if 0 <= new_x < len(mapray[0]) and 0 <= new_y < len(mapray) and mapray[new_y][new_x] == 0:
if dfs(new_x, new_y, mapray, visited, rx, ry, path):
path.append(directions[i])
return True
return False
def main():
x, y = map(int, input("输入初始的坐标(x, y): ").split())
lenx = int(input("输入x轴的长度: "))
rx, ry = map(int, input("输入终点坐标: ").split())
mapray = map_input(lenx)
print(mapray)
#这一步可删,输出的是地图
visited = [[False for _ in range(len(mapray[0]))] for _ in range(len(mapray))]
path = []
if dfs(x, y, mapray, visited, rx, ry, path):
print("成功走到")
print("路线:", path[::-1])
else:
print("走不通,失败!")
if __name__ == "__main__":
main()
实验数据:
输入初始的坐标(x, y): 0 0
输入x轴的长度: 9
输入终点坐标: 4 4
请输入地图数据,以逗号分隔: 0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,1
[[0, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1, 0, 1, 1], [1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 1, 1]]
成功走到
路线: ['d', 's', 'd', 's', 's', 'd', 's', 'd']