Leetcode 1765: Map of Highest Peak

grid47
grid47
Exploring patterns and algorithms
May 14, 2024 7 min read

Given a 2D grid where each cell is either water (1) or land (0), assign heights to the land cells such that the height difference between adjacent cells is at most 1. The goal is to maximize the height values of land cells while ensuring the height of water cells is 0. Return the grid with assigned heights.
Problem
Approach
Steps
Complexity
Input: The input consists of a matrix where each element is either 0 (land) or 1 (water).
Example: isWater = [[0,0,1],[1,0,0],[0,0,0]]
Constraints:
• m == isWater.length
• n == isWater[i].length
• 1 <= m, n <= 1000
• isWater[i][j] is 0 or 1
• There is at least one water cell
Output: Return a matrix of the same size where each land cell has a height and the height difference between adjacent cells is at most 1.
Example: Output: [[1,1,0],[0,1,1],[1,2,2]]
Constraints:
• Each cell's height is non-negative
• The height difference between adjacent cells is at most 1
Goal: To assign the maximum possible height to each land cell while ensuring the height difference between adjacent cells is at most 1.
Steps:
• Initialize a queue with the positions of all water cells, and set their heights to 0.
• Perform a breadth-first search (BFS) from each water cell to assign heights to adjacent land cells.
• Ensure that the height difference rule is satisfied while maximizing the heights.
Goal: The constraints specify the size limits for the matrix and the cells.
Steps:
• 1 <= m, n <= 1000
• The matrix will contain at least one water cell
Assumptions:
• It is guaranteed that there is at least one water cell in the matrix.
Input: isWater = [[0,1],[0,0]]
Explanation: In this case, the water cell has height 0, and the adjacent land cell is assigned the maximum possible height of 1. The next land cell is assigned height 2, adhering to the height difference rule.

Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]
Explanation: The water cells are at positions (0,2) and (1,0). Heights are assigned starting from the water cells, ensuring that the maximum height is 2 for the land cells.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus