LeetCode solutions

2101. Last Day Where You Can Still Cross

My accepted Python solution to LeetCode problem 2101, Last Day Where You Can Still Cross, running in 1860ms.

  • Difficulty: Hard
  • Python
  • Runtime 1860ms
  • Memory 27.1MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 1860ms, memory 27.1MB, accepted 2025-12-31.

python
class Solution:
    def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:
        from collections import deque
        
        def canCross(day):
            water = set()
            for i in range(day):
                water.add((cells[i][0] - 1, cells[i][1] - 1))
            
            queue = deque()
            visited = set()
            for c in range(col):
                if (0, c) not in water:
                    queue.append((0, c))
                    visited.add((0, c))
            
            directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
            while queue:
                r, c = queue.popleft()
                if r == row - 1:
                    return True
                for dr, dc in directions:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < row and 0 <= nc < col and (nr, nc) not in water and (nr, nc) not in visited:
                        visited.add((nr, nc))
                        queue.append((nr, nc))
            return False
        
        left, right = 1, len(cells)
        while left < right:
            mid = (left + right + 1) // 2
            if canCross(mid):
                left = mid
            else:
                right = mid - 1
        return left

Source