序言
比较经典的迷宫问题:
由空地(用 0 表示)和墙(用 1 表示)组成的迷宫 maze 中有一个球。球可以途经空地向 上、下、左、右 四个方向滚动,且在遇到墙壁前不会停止滚动。当球停下时,可以选择向下一个方向滚动。
给你一个大小为 m x n 的迷宫 maze ,以及球的初始位置 start 和目的地 destination ,其中 start = [startrow, startcol] 且 destination = [destinationrow, destinationcol] 。请你判断球能否在目的地停下:如果可以,返回 true ;否则,返回 false
输入:maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
输出:true
输入:maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
输出:false
思路如下:
def hasPath( maze, start, destination):
row, col = len(maze),len(maze[0])
stack = []
stack.append(start)
dire = ((0,1),(0,-1),(1,0),(-1,0))
#表示 上下左右的方向 direction
dp = [[False]*col for _ in range(row)]
dp[start[0]][start[1]] = True
while stack:
i,j = stack.pop(0)
if [i,j] == destination: return True
for di,dj in dire:
#========================
ni = i + di
nj = j + dj
while 0<= ni < row and 0 <= nj < col and maze[ni][nj] == 0:
ni += di
nj += dj
ni -= di
nj -= dj
#直到撞墙了,才停下的意思
#此时的[ni,nj]表示撞到墙后的格子
#==========================
if dp[ni][nj]:continue
else:
dp[ni][nj] = True
stack.append([ni,nj])
return False
函数解释:
pop()函数 VS popleft()函数
(1)pop函数
pop是用于stack中的,即list这些 [] 数据类型
例子如下:
stack = [1, 2, 3, 4]
print(stack.pop(1))
#可以带参数 1表示位置,即第二位要pop掉 ;如果没有数字,默认为最后一位
print(stack)
输出:
2
[1, 3, 4, 6]
(2)popleft函数
pooleft是用于collections中,不可以带参数,表示pop掉最左边的元素。
特别是 deque数据类型:
deque 对象类似于list列表,但比list列表操作更快
from collections import deque
name = deque(["aaa", "bbb", "ccc", "ddd",'xxx', 'yyy'])
print(name.popleft()) #不可以带参数
print(name)
输出:
aaa
deque(['bbb', 'ccc', 'ddd', 'xxx', 'yyy'])
既然这里提到了deque数据对象,那么我们来了解一下deque是怎么回事
(3)deque
deque是类似于list的数据类型
from collections import deque
d=deque('abcdefg')
d.remove('c')
print(d)
输出:
deque(['a', 'b', 'd', 'e', 'f', 'g'])
想要加入东西可以用extend或者append都可以
其中特别注意的是 如果想要加入再deque的左边,可以用extendleft 来添加
类似题–迷宫II
题目505-迷宫:
由空地和墙组成的迷宫中有一个球。球可以向上下左右四个方向滚动,但在遇到墙壁前不会停止滚动。当球停下时,可以选择下一个方向。
给定球的起始位置,目的地和迷宫,找出让球停在目的地的最短距离。距离的定义是球从起始位置(不包括)到目的地(包括)经过的空地个数。如果球无法停在目的地,返回 -1。
这里迷宫的设定跟第一题差不多,但是这里要求返回的是找出让球停在目的地的最短距离。所以我们这次需要记录步数。
def shortestDistance( maze, start, destination):
row, col = len(maze), len(maze[0])
stack = []
stack.append(start)
dp = [[float('inf')]*col for _ in range(row)]
dp[start[0]][start[1]] = 0
dire = ((0,1),(0,-1),(1,0),(-1,0))
step = 0
while stack:
i,j = stack.pop(0)
for di,dj in dire:
#==============================================================
ni = i + di
nj = j + dj
step = 1
while 0<= ni < row and 0 <= nj < col and maze[ni][nj] == 0:
ni += di
nj += dj
step += 1
ni -= di
nj -= dj
step -= 1
#=============================================================
if dp[i][j] + step < dp[ni][nj]:
#不走回去的路,即步数更小的格子,如果是有两条路,其中撞上,
#也会比较哪个格子的步数更小,从而取更小的那条路
dp[ni][nj] = dp[i][j] + step
stack.append((ni,nj))
#=============================================================
if dp[destination[0]][destination[1]] == float('inf'): return -1
else: return dp[destination[0]][destination[1]]