def checkio(labyrinth):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] # East, West, South, North
def is_valid_move(x, y):
return 0 <= x < len(labyrinth) and 0 <= y < len(labyrinth[0]) and labyrinth[x][y] == 0 # 判断是否在迷宫内,且是否是空格区域
def dfs(x, y, path): #初始的x,y是起点位置的x,y,即需要被定为(1,1)
if (x, y) == (10, 10):
return ''.join(move[0] for move in path)
for dx, dy in directions:
nx, ny = x + dx, y + dy
if is_valid_move(nx, ny):
labyrinth[x][y] = 2 # Mark the current cell as visited
path.append(('S' if dx == 1 else 'N' if dx == -1 else 'E' if dy == 1 else 'W')) #根据坐标值确定方向
result = dfs(nx, ny, path)
if result is not None:
return result
path.pop() # Backtrack
labyrinth[x][y] = 0 # Restore the cell to its original state
return None
result = dfs(1, 1, [])
return result if result is not None else "No path found"
Checkio Open Labyrinth
于 2024-03-29 00:24:30 首次发布