Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import deque
- class Solution:
- def is_valid(self, ri, ci, rn, cn):
- if ri < 0 or ri >= rn or ci < 0 or ci >= cn:
- return False
- return True
- def is_reachable(self, start_ri, start_ci, target_ri, target_ci, box_ri, box_ci, grid):
- rn = len(grid)
- cn = len(grid[0])
- if not self.is_valid(target_ri, target_ci, rn, cn) or grid[target_ri][target_ci] == '#':
- return False
- q = deque()
- q.append((start_ri, start_ci))
- visited = set()
- visited.add((start_ri, start_ci))
- moves = [(-1, 0), (0, 1), (1, 0), (0, -1)]
- while q:
- ri, ci = q.popleft()
- if ri == target_ri and ci == target_ci:
- return True
- for kr, kc in moves:
- xri = ri + kr
- xci = ci + kc
- if self.is_valid(xri, xci, rn, cn) and \
- grid[xri][xci] != '#' and \
- (xri != box_ri or xci != box_ci) and \
- (xri, xci) not in visited:
- q.append((xri, xci))
- visited.add((xri, xci))
- return False
- def minPushBox(self, grid: List[List[str]]) -> int:
- rn = len(grid)
- cn = len(grid[0])
- for ri in range(rn):
- for ci in range(cn):
- if grid[ri][ci] == 'T':
- t_ri, t_ci = ri, ci
- elif grid[ri][ci] == 'B':
- b_ri, b_ci = ri, ci
- elif grid[ri][ci] == 'S':
- s_ri, s_ci = ri, ci
- q = deque()
- q.append((b_ri, b_ci, s_ri, s_ci, 0))
- visited = set()
- visited.add((b_ri, b_ci, s_ri, s_ci))
- moves = [(-1, 0), (0, 1), (1, 0), (0, -1)]
- while q:
- b_ri, b_ci, s_ri, s_ci, lvl = q.popleft()
- if b_ri == t_ri and b_ci == t_ci:
- return lvl
- for kr, kc in moves:
- next_b_ri = b_ri + kr
- next_b_ci = b_ci + kc
- s_push_ri = b_ri + -1 * (kr)
- s_push_ci = b_ci + -1 * (kc)
- if self.is_valid(next_b_ri, next_b_ci, rn, cn) and \
- grid[next_b_ri][next_b_ci] != '#' and \
- self.is_reachable(s_ri, s_ci, s_push_ri, s_push_ci, b_ri, b_ci, grid) and \
- (next_b_ri, next_b_ci, s_push_ri, s_push_ci) not in visited:
- q.append((next_b_ri, next_b_ci, s_push_ri, s_push_ci, lvl+1))
- visited.add((next_b_ri, next_b_ci, s_push_ri, s_push_ci))
- return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement