Checkio Open Labyrinth

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" 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值