leetcode 864 获得钥匙的最短路径

题目:
We are given a 2-dimensional grid. “.” is an empty cell, “#” is a wall, “@” is the starting point, (“a”, “b”, …) are keys, and (“A”, “B”, …) are locks.

We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can’t walk over a lock unless we have the corresponding key.

For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

Return the lowest number of moves to acquire all keys. If it’s impossible, return -1.

Example 1:

Input: ["@.a.#","###.#",“b.A.B”]
Output: 8
Example 2:

Input: ["@…aA","…B#.","…b"]
Output: 6

Note:

1 <= grid.length <= 30
1 <= grid[0].length <= 30
grid[i][j] contains only ‘.’, ‘#’, ‘@’, ‘a’-‘f’ and ‘A’-‘F’
The number of keys is in [1, 6]. Each key has a different letter and opens exactly one lock.
题解:
class Solution(object):
def shortestPathAllKeys(self, grid):
“”"
:type grid: List[str]
:rtype: int
“”"
final,R,C,si,sj=0,len(grid),len(grid[0]),0,0
for i in range®:
for j in range©:
if grid[i][j] in ‘abcdef’:
final|=1<<(ord(grid[i][j])-ord(‘a’))
elif grid[i][j]’@’:
si,sj=i,j
q,memo=[(0,si,sj,0)],set()
while q:
move,i,j,state=heapq.heappop(q)
if state
final:return move
for x,y in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):
if 0<=x<R and 0<=y<C and grid[x][y]!=’#’:
if grid[x][y].isupper() and not state&1<<(ord(grid[x][y].lower())-ord(‘a’)):
continue
newstate=ord(grid[x][y])>=ord(‘a’) and state|1<<(ord(grid[x][y])-ord(‘a’)) or state
if (newstate,x,y) not in memo:
heapq.heappush(q,(move+1,x,y,newstate))
memo.add((newstate,x,y))

    return -1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值