Problem Description
Given a binary matrix of dimensions row x col with initially all cells as land (0), cells become water (1) day by day in the order provided by the array cells. The goal is to determine the last day on which there is still a valid path from any cell in the top row to any cell in the bottom row, moving only in the four cardinal directions and only through land cells.
Key Insights
- The problem is essentially about determining connectivity on a grid that changes over time.
- A binary search can be used on the day index because if it is possible to cross on a certain day, it may still be possible on earlier days.
- For a given day, use BFS/DFS (or Union Find) on the grid to check if there is a path from the top row to the bottom row.
- The grid state for each day is constructed by marking the cells flooded up to that day.
- Alternatively, union-find can be used to maintain connectivity as cells switch from land to water.
Space and Time Complexity
Time Complexity: O((row * col) * log(row * col)) – binary search over the days with grid traversal each time. Space Complexity: O(row * col) – storing the grid and auxiliary data structures for BFS/DFS or union-find.
Solution
We use a binary search approach on the number of days. For a given day, we simulate the grid by marking the first mid cells as water. We then perform a BFS starting from all land cells in the top row, checking if we can reach any cell in the bottom row. By adjusting our binary search bounds based on the BFS result, we can efficiently find the last day where a path exists. The key trick here is to reverse the typical thinking: instead of trying every day sequentially, we leverage binary search to reduce the number of full grid checks.