阿里2020.3.23笔试题——走迷宫

问题描述

小强在玩一个走迷宫的游戏,他操控的人物现在位于迷宫的起点,他的目标是尽快的达到终点。每一次他可以选择花费一个时间单位向上或者向下或者向左或者向右走一格,或是使用自己的对称飞行器花费一个时间单位瞬移到关于当前自己点中心对称的格子,且每一次移动的目的地不能存在障碍物。具体来数说,设当前迷宫有 n n n m m m列,如果当前小强操控的人物位于点 A ( x , y ) A(x, y) A(x,y),那么关于点 A A A中心对称的格子 B ( x ′ , y ′ ) B(x', y') B(x,y)满足 x + x ′ = n + 1 x + x' = n + 1 x+x=n+1 y + y ′ = m + 1 y + y' = m + 1 y+y=m+1。需要注意的是,对称飞行器最多使用5次。

问题分析

典型的搜索问题,在考虑中心对称的情况下,使用bfs或者dfs即可解决。

代码示例

from collections import deque

n, m = map(int, input().split('  '))

matrix = []
for i in range(n):
    matrix.append(list(input()))

si, sj = 0, 0

is_found = False
for i in range(n):
    for j in range(m):
        if matrix[i][j] == 'S':
            si = i
            sj = j
            is_found = True
            break
    if is_found:
        break

directions = [(1, 0), (0, -1), (-1, 0), (0, 1)] # 上下左右

# bfs
queue = deque()
queue.appendleft((si, sj, 5, 0))

while queue:
    row, col, cnt, step = queue.pop()
    if matrix[row][col] == 'E':
        break
    matrix[row][col] = '#'
    if 0 <= row + 1 < n and matrix[row + 1][col] != '#':
        queue.appendleft((row + 1, col, cnt, step + 1))
    if 0 <= col - 1 < m and matrix[row][col - 1] != '#':
        queue.appendleft((row, col - 1, cnt, step + 1))
    if 0 <= row -1 < n and matrix[row - 1][col] != '#':
        queue.appendleft((row - 1, col, cnt, step + 1))
    if 0 <= col + 1 < m and matrix[row][col + 1] != '#':
        queue.appendleft((row, col + 1, cnt, step + 1))
    if matrix[n - 1 - row][m - 1 - col] != '#' and 0 <= cnt:
        queue.appendleft((n - 1 - row, m - 1 - col, cnt - 1, step + 1))

print(step)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值