BFS=广度优先搜索(借助队列)
DFS=深度优先搜索(借助栈)
树的前序遍历等价于树的广度优先搜索
LeetCode - 909 蛇梯棋
https://leetcode-cn.com/problems/snakes-and-ladders/
题目类似于飞行棋,如果当前位于 x,下一步 y 可以在 [x+1, x+6] 位置任选,但是如果下一步坐标内有传送捷径,则必须使用且使用一次捷径。
——单向图,求最短路径
有一点简单的数学推导,就是“传送捷径”本来是一个一维数组,题目给定时,是把一维数组按S型弯折后以二维数组的形式给出的。
import queue
class Solution(object):
__n = None
__board = None
def __TransistDest(self, origin):
quotient = (origin - 1) // self.__n
remainder = (origin - 1) % self.__n
row = self.__n - 1 - quotient
if (quotient % 2):
column = self.__n - 1 - remainder
else:
column = remainder
return self.__board[row][column]
def snakesAndLadders(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
self.__n = len(board)
self.__board = board
bestStepsCnt = [-1] * (self.__n ** 2 + 1)
bfsQueue = queue.SimpleQueue()
bestStepsCnt[1] = 0
bfsQueue.put(1)
while(not bfsQueue.empty()):
start = bfsQueue.get()
startStepsCnt = bestStepsCnt[start]
for dest in range(start + 1, start + 6 + 1):
if (dest > self.__n ** 2):
break
transist = self.__TransistDest(dest)
if(transist > 0):
dest = transist
if (dest == self.__n ** 2):
return startStepsCnt + 1
if (bestStepsCnt[dest] < 0):
bestStepsCnt[dest] = startStepsCnt + 1
bfsQueue.put(dest)
return -1