Problem Description
Given an m x n matrix isWater where each cell is either land (0) or water (1), assign non-negative heights to all cells such that water cells have height 0 and any two adjacent cells differ in height by at most 1. The goal is to maximize the maximum height in the matrix. This problem is equivalent to finding the minimum distance from each cell to a water cell.
Key Insights
- Water cells are fixed with height 0 and act as BFS sources.
- A multi-source BFS calculates the minimum distance from any land cell to its nearest water cell.
- Each cell’s height will be its distance from the nearest water cell, ensuring the adjacent difference is at most 1.
- This approach guarantees the maximum height in the matrix is maximized.
Space and Time Complexity
Time Complexity: O(m * n) – each cell is processed once in the BFS. Space Complexity: O(m * n) – space needed for the queue and the result matrix.
Solution
We use a multi-source Breadth-First Search (BFS) starting from all water cells (cells with value 1 in isWater). Initially, all water cells are enqueued with height 0. As we pop a cell from the queue, we update its adjacent land neighbors with height = current height + 1 if they have not been visited yet. This BFS guarantees that each cell gets the minimum distance to a water cell, which satisfies the height assignment rules.