pass 909 bfs medium
This commit is contained in:
parent
98bf27748a
commit
364ad7a999
46
909-240525-pass/main.py
Normal file
46
909-240525-pass/main.py
Normal file
@ -0,0 +1,46 @@
|
||||
class Solution:
|
||||
def snakesAndLadders(self, board: List[List[int]]) -> int:
|
||||
ans = 0
|
||||
n = len(board)
|
||||
n = n - 1
|
||||
length = n + 1
|
||||
que = [(1,0)]
|
||||
idx = 0
|
||||
flag = [0 for i in range((n+1)*(n+1))]
|
||||
def add_node(que, idx, node):
|
||||
if len(que) <= idx:
|
||||
que.append(node)
|
||||
else:
|
||||
que[idx] = node
|
||||
def move(idx):
|
||||
row = 0
|
||||
column = idx % (n + 1)
|
||||
if idx % (n + 1) == 0: row -= 1
|
||||
row += idx // (n + 1)
|
||||
row = n - row
|
||||
oe = idx // (n + 1) % 2
|
||||
if idx % (n + 1) == 0: oe = 1 - oe
|
||||
if column == 0: column = n + 1
|
||||
column -= 1
|
||||
if oe == 1: column = n - column
|
||||
return (row, column)
|
||||
front = 0
|
||||
while idx - front >= 0:
|
||||
node = que[front]
|
||||
front += 1
|
||||
step = node[1]
|
||||
cur_loc = node[0]
|
||||
if flag[cur_loc] == 1: continue
|
||||
flag[cur_loc] = 1
|
||||
if cur_loc + 6 >= length * length:
|
||||
return step + 1
|
||||
for i in range(1, 7):
|
||||
(row, column) = move(i + cur_loc)
|
||||
if board[row][column]!= -1:
|
||||
if board[row][column] == length * length: return step + 1
|
||||
idx += 1
|
||||
add_node(que, idx, (board[row][column], step + 1))
|
||||
else:
|
||||
idx += 1
|
||||
add_node(que, idx, (i + cur_loc, step + 1))
|
||||
return -1
|
Loading…
Reference in New Issue
Block a user