1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class Solution: def maximumMinutes(self, grid: List[List[int]]) -> int: n=len(grid[0]) m=len(grid) times=[[0x7fffffff]*n for _ in range(m)] q=deque() directions=[[0,-1],[0,1],[1,0],[-1,0]] for i in range(m): for j in range(n): if grid[i][j]==1: q.append([i,j]) elif grid[i][j]==2: times[i][j]=-1 now=0 h=set() while q: length=len(q) for _ in range(length): i,j=q.popleft() times[i][j]=now h.add((i,j)) for dx,dy in directions: x,y=i+dx,j+dy if 0<=x<m and 0<=y<n and grid[x][y]!=2 and (x,y) not in h: q.append((x,y)) now+=1 people=[[0x7fffffff]*n for _ in range(m)] q.append((0,0)) h.clear() now=0 h=set() while q: length=len(q) for _ in range(length): i,j=q.popleft() people[i][j]=now h.add((i,j)) for dx,dy in directions: x,y=i+dx,j+dy if 0<=x<m and 0<=y<n and grid[x][y]!=2 and grid[x][y]!=1 and (x,y) not in h: q.append((x,y)) now+=1 if times[-1][-1]<people[-1][-1] or people[-1][-1]==0x7fffffff: return -1 if times[0][0]==0: return -1 if times[-1][-1]==0x7fffffff: return 1000000000 maxNeed=times[-1][-1]-people[-1][-1] if times[-1][-2]>people[-1][-2]+maxNeed or times[-2][-1]>people[-2][-1]+maxNeed: return maxNeed return maxNeed-1
|