Skip to content

Commit ebc37e9

Browse files
committed
Time: 4981 ms (31.51%), Space: 25.6 MB (97.26%) - LeetHub
1 parent 969fbb6 commit ebc37e9

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from collections import deque
2+
from typing import List
3+
4+
5+
class Solution:
6+
7+
dir = [(0, 1), (0, -1), (1, 0), (-1, 0)]
8+
9+
def maximumSafenessFactor(self, grid: List[List[int]]) -> int:
10+
n = len(grid)
11+
multiSourceQueue = deque()
12+
for i in range(n):
13+
for j in range(n):
14+
if grid[i][j] == 1:
15+
multiSourceQueue.append((i, j))
16+
grid[i][j] = 0
17+
else:
18+
grid[i][j] = -1
19+
while multiSourceQueue:
20+
size = len(multiSourceQueue)
21+
while size > 0:
22+
curr = multiSourceQueue.popleft()
23+
for d in self.dir:
24+
di, dj = curr[0] + d[0], curr[1] + d[1]
25+
val = grid[curr[0]][curr[1]]
26+
if self.isValidCell(grid, di, dj) and grid[di][dj] == -1:
27+
grid[di][dj] = val + 1
28+
multiSourceQueue.append((di, dj))
29+
size -= 1
30+
start, end, res = 0, 0, -1
31+
for i in range(n):
32+
for j in range(n):
33+
end = max(end, grid[i][j])
34+
while start <= end:
35+
mid = start + (end - start) // 2
36+
if self.isValidSafeness(grid, mid):
37+
res = mid
38+
start = mid + 1
39+
else:
40+
end = mid - 1
41+
return res
42+
43+
def isValidCell(self, grid, i, j) -> bool:
44+
n = len(grid)
45+
return 0 <= i < n and 0 <= j < n
46+
47+
def isValidSafeness(self, grid, minSafeness) -> bool:
48+
n = len(grid)
49+
if grid[0][0] < minSafeness or grid[n - 1][n - 1] < minSafeness:
50+
return False
51+
traversalQueue = deque([(0, 0)])
52+
visited = [[False] * n for _ in range(n)]
53+
visited[0][0] = True
54+
while traversalQueue:
55+
curr = traversalQueue.popleft()
56+
if curr[0] == n - 1 and curr[1] == n - 1:
57+
return True
58+
for d in self.dir:
59+
di, dj = curr[0] + d[0], curr[1] + d[1]
60+
if self.isValidCell(grid, di, dj) and not visited[di][dj] and grid[di][dj] >= minSafeness:
61+
visited[di][dj] = True
62+
traversalQueue.append((di, dj))
63+
return False
64+
65+
66+
grid = [[1, 0, 0], [0, 0, 0], [0, 0, 1]]
67+
print(Solution().maximumSafenessFactor(grid))

0 commit comments

Comments
 (0)