【leetcode】909. Snakes and Ladders
阿新 • • 發佈:2018-09-25
pen only 代碼 連續 理解 如果 tla you end
題目如下:
解題思路:天坑題,不在於題目多難,而是要理解題意。題目中有兩點要特別註意,一是“You choose a destination square S
with number x+1
, x+2
, x+3
, x+4
, x+5
, or x+6
, provided this number is <= N*N
.” 這裏最大可以移動的x+6中的6真的就是數字6啊,不是例子中的N=6的6,可以理解成是擲骰子。二是“Note that you only take a snake or ladder at most once per move: if the destination to a snake or ladder is the start of another snake or ladder, you do not continue moving. ” 這裏的意思是不能連續坐梯子,例如如果一個數字是通過梯子到達的,那麽即使這個數字本身有梯子,也不能繼續坐了,必須移動x+1~x+6中的某一步。理解了題意後,其實這題就非常簡單了,DFS或者BFS都行。
代碼如下:
class Solution(object): def getLadderDestination(self,v,N): for i in range(1,N+1): if v <= i*N: break r = N-i if (i) % 2 == 1: c = v - ((i-1)*N + 1) else: c = i*N - v return (r,c) def snakesAndLadders(self, board):""" :type board: List[List[int]] :rtype: int """ N = len(board) #endPosition = None if N % 2 == 0: endPosition = (0,0) else: endPosition = (0,N-1) visit = [[N*N+1] * N for i in range(N)] queue = [(1,0)] visit[N-1][0] = 0 while len(queue) > 0: v,step = queue.pop(0) #x,y = self.getLadderDestination(v,N) #visit[x][y] = min(visit[x][y],step) for i in range(v+1,min(N*N,v+6)+1): x,y = self.getLadderDestination(i,N) if board[x][y] > 0: ladder_x, ladder_y = self.getLadderDestination(board[x][y], N) if board[ladder_x][ladder_y] == 44: pass if visit[ladder_x][ladder_y] > step + 1: queue.append((board[x][y], step + 1)) visit[ladder_x][ladder_y] = min(step + 1, visit[ladder_x][ladder_y]) elif visit[x][y] > step+1: queue.append((i, step + 1)) visit[x][y] = min(visit[x][y],step+1) #print visit return visit[endPosition[0]][endPosition[1]] if visit[endPosition[0]][endPosition[1]] != N*N+1 else -1
【leetcode】909. Snakes and Ladders