<p>You are given a <strong>0-indexed</strong> 2D matrix <code>grid</code> of size <code>n x n</code>, where <code>(r, c)</code> represents:</p>

<ul>
	<li>A cell containing a thief if <code>grid[r][c] = 1</code></li>
	<li>An empty cell if <code>grid[r][c] = 0</code></li>
</ul>

<p>You are initially positioned at cell <code>(0, 0)</code>. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.</p>

<p>The <strong>safeness factor</strong> of a path on the grid is defined as the <strong>minimum</strong> manhattan distance from any cell in the path to any thief in the grid.</p>

<p>Return <em>the <strong>maximum safeness factor</strong> of all paths leading to cell </em><code>(n - 1, n - 1)</code><em>.</em></p>

<p>An <strong>adjacent</strong> cell of cell <code>(r, c)</code>, is one of the cells <code>(r, c + 1)</code>, <code>(r, c - 1)</code>, <code>(r + 1, c)</code> and <code>(r - 1, c)</code> if it exists.</p>

<p>The <strong>Manhattan distance</strong> between two cells <code>(a, b)</code> and <code>(x, y)</code> is equal to <code>|a - x| + |b - y|</code>, where <code>|val|</code> denotes the absolute value of val.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/07/02/example1.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[1,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/07/02/example2.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,1],[0,0,0],[0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>

<p><strong class="example">Example 3:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2023/07/02/example3.png" style="width: 362px; height: 242px;" />
<pre>
<strong>Input:</strong> grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The path depicted in the picture above has a safeness factor of 2 since:
- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.
- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.
It can be shown that there are no other paths with a higher safeness factor.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= grid.length == n &lt;= 400</code></li>
	<li><code>grid[i].length == n</code></li>
	<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
	<li>There is at least one thief in the <code>grid</code>.</li>
</ul>

class Solution:
    
    direction = [(1,0), (-1,0), (0,1), (0,-1)]

    def maximumSafenessFactor(self, grid: List[List[int]]) -> int:
        # 可以上下左右移動，找出一條安全係數最高的路徑。安全係數的定義：離小偷(cell=1)越遠越高，manhattan distance：|a-x|+|b-y|
        # brute force: 算出每個cell離小偷最短的距離，來取得最安全的路徑。比較完整的說法 => 找到每格安全係數的一種方法是遍歷grid中每個格子，並找到每格與所有小偷的距離，然後選擇最小距離作為該格的安全係數。這種暴力法的時間複雜度為O(n^4)，無法滿足問題限制(constraints)。因此，需要更優化的方法。
        # To optimize the solution：(1)利用multi-source BFS特性，與其找到每個cell與所有小偷的距離，不如反過來：找到所有小偷與每個cell的距離。 (2) Apply binary search to find the maximum safeness factor for which a path exists from the source to the destination cell.
        # BFS + Binary Search: time O(n^2 * logn), space O(n^2)
        """
        n = len(grid)
        multi_source_bfs = deque()
        # find thief and change thief cell 0->1, empty cell 0->-1
        for i in range(n):
            for j in range(n):
                if grid[i][j] == 1:
                    multi_source_bfs.append((i, j))
                    grid[i][j] = 0
                else:
                    grid[i][j] = -1

        # update cell = distance of the thief，不用考慮出入口
        while multi_source_bfs:
            thief_count = len(multi_source_bfs)
            while thief_count > 0:
                
                curr_thief = multi_source_bfs.popleft()
                
                for dir_i, dir_j in self.direction:
                    next_i = curr_thief[0] + dir_i
                    next_j = curr_thief[1] + dir_j

                    if ((0 <= next_i < n) 
                        and (0 <= next_j < n) 
                        and grid[next_i][next_j]) == -1:

                        grid[next_i][next_j] = grid[curr_thief[0]][curr_thief[1]] + 1
                        multi_source_bfs.append((next_i, next_j))
                thief_count -= 1

        #binary search to find maximum path，一般都從頭找到尾，用bs從中間的距離開始找，可以從n降到logn(概念：如果中間值safe，那答案一定在後段，如果中間值不安全，那答案在前段)
        start, end, res = 0, 0, -1
        for i in range(n):
            for j in range(n):
                #找出grid中小偷到cell的最遠距離
                end = max(end, grid[i][j])
        while start <= end:
            mid = (end + start) // 2
            if self.isValidSafe(grid, mid): 
                res = mid
                start = mid + 1
            else:
                end = mid - 1
        return res
    
    #概念：如果中間值safe，那答案一定在後段，如果中間值不安全，那答案在前段
    def isValidSafe(self, grid, mid) -> bool:
        n = len(grid)
        #檢查出入口有無大於安全值(也就是中間值)，符合才代表此路安全
        if grid[0][0] < mid or grid[n-1][n-1] < mid:
            return False

        path = deque([(0, 0)])
        visited = [[False] * n for _ in range(n)]
        visited[0][0] = True
        while path:
            curr_path = path.popleft()

            #代表安全走到出口了
            if curr_path[0] == (n-1) and curr_path[1] == (n-1):
                return True
            
            for dir_i, dir_j in self.direction:
                next_i = curr_path[0] + dir_i
                next_j = curr_path[1] + dir_j
                #檢查下一步確認沒有走過而且符合安全值
                if ((0 <= next_i < n) 
                    and (0 <= next_j < n) 
                    and not visited[next_i][next_j]
                    and grid[next_i][next_j] >= mid):
                    #記錄走過並放到queue裡繼續走
                    visited[next_i][next_j] = True
                    path.append((next_i, next_j))
        
        #直到path走完都沒有走到出口，代表此路不安全
        return False
    """
        n = len(grid)

        thieves = deque()
        for i in range(n):
            for j in range(n):
                if grid[i][j] == 1:
                    thieves.append((i, j))
                    grid[i][j] = 0
                else:
                    grid[i][j] = -1

        while thieves:
            thief_count = len(thieves)
            while thief_count > 0:
                curr_thief = thieves.popleft()
                for d in self.direction:
                    next_i, next_j = curr_thief[0] + d[0], curr_thief[1] + d[1]
                    if ((0 <= next_i < n) 
                        and (0 <= next_j < n) 
                        and grid[next_i][next_j]) == -1:
                        grid[next_i][next_j] = grid[curr_thief[0]][curr_thief[1]] + 1
                        thieves.append((next_i, next_j))
                thief_count -= 1
        
        pq = [[-grid[0][0], 0, 0]] 
        # [maximum_safeness_till_now, x-coordinate, y-coordinate]
        grid[0][0] = -1 # Mark the source cell as visited

        # BFS to find the path with maximum safeness factor
        while pq:
            safeness, i, j = heapq.heappop(pq)
            
            if i == n - 1 and j == n - 1:
                return -safeness
            
            for d in self.direction:
                di, dj = i + d[0], j + d[1]
                # Check if the neighboring cell is valid and unvisited
                if (0 <= di < n) and (0 <= dj < n) and grid[di][dj] != -1:
                    heapq.heappush(pq, [-min(-safeness, grid[di][dj]), di, dj])
                    grid[di][dj] = -1

        return -1
3261