classSolution: defmaximumSafenessFactor(self, grid: List[List[int]]) -> int: n = len(grid) # 多源BFS計算每個點到最近的 1 的曼哈頓距離 dist = [[-1] * n for _ inrange(n)] q = deque() for i inrange(n): for j inrange(n): if grid[i][j] == 1: dist[i][j] = 0 q.append((i, j, 0)) while q: i, j, d = q.popleft() for nx, ny in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if0 <= nx < n and0 <= ny < n and dist[nx][ny] == -1: dist[nx][ny] = d + 1 q.append((nx, ny, d+1)) # 對答案二分,這裡使用BFS來檢查是否存在一條路徑 defcheck(x): if dist[0][0] < x: returnFalse visited = [[False] * n for _ inrange(n)] q = deque([(0, 0)]) visited[0][0] = True while q: i, j = q.popleft() if i == n-1and j == n-1: returnTrue for nx, ny in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if0 <= nx < n and0 <= ny < n andnot visited[nx][ny] and dist[nx][ny] >= x: visited[nx][ny] = True q.append((nx, ny)) returnFalse left, right = 0, 2*n-2# [0, 2n-2] while left <= right: # 區間不為空 mid = (left + right) // 2 if check(mid): left = mid + 1 else: right = mid - 1 return right
classSolution: defmaximumSafenessFactor(self, grid: List[List[int]]) -> int: n = len(grid) # 多源BFS計算每個點到最近的 1 的曼哈頓距離 dist = [[-1] * n for _ inrange(n)] q = deque() groups = defaultdict(list) # 保存距離到點的對應關係 for i inrange(n): for j inrange(n): if grid[i][j] == 1: dist[i][j] = 0 q.append((i, j, 0)) groups[0].append((i, j)) while q: i, j, d = q.popleft() for nx, ny in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if0 <= nx < n and0 <= ny < n and dist[nx][ny] == -1: dist[nx][ny] = d + 1 q.append((nx, ny, d+1)) groups[d+1].append((nx, ny)) # DSU fa = [i for i inrange(n*n)] # 將二維座標轉換為一維 deffind(x): if x != fa[x]: fa[x] = find(fa[x]) return fa[x] defunion(x, y): x, y = find(x), find(y) if x != y: fa[x] = y # 從最大距離開始枚舉 x for d inrange(max(groups.keys()), 0, -1): for i, j in groups[d]: for nx, ny in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if0 <= nx < n and0 <= ny < n and dist[nx][ny] >= d: # 周圍有距離 >= x 的點,則使其連通 union(i*n+j, nx*n+ny) if find(0) == find(n*n-1): # 起點和終點在同一個集合中 return d return0