1765. Map of Highest Peak
Explanation
To solve this problem, we can use a breadth-first search (BFS) approach starting from all water cells. We initialize a queue with all water cells and assign them a height of 0. Then, we traverse the cells in the queue and assign heights to their neighboring land cells based on the water cells' heights. We continue this process until all cells have been visited.
By assigning heights based on the water cells, we ensure that the height difference between adjacent cells is at most 1. This way, we can maximize the overall height in the matrix.
Algorithm:
- Initialize a queue and add all water cells to the queue with a height of 0.
- Perform a BFS traversal on the matrix:
- For each cell in the queue:
- Pop the cell from the queue.
- Explore its neighbors:
- If the neighbor is a valid land cell and has not been visited yet, assign it a height based on the current cell's height.
- Add the neighbor to the queue.
- For each cell in the queue:
- Return the resulting height matrix.
Time Complexity:
The time complexity of this approach is O(m * n), where m is the number of rows and n is the number of columns in the matrix.
Space Complexity:
The space complexity is also O(m * n) to store the queue and the resulting height matrix.
class Solution {
public int[][] highestPeak(int[][] isWater) {
int m = isWater.length;
int n = isWater[0].length;
int[][] height = new int[m][n];
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
Arrays.fill(height[i], -1);
for (int j = 0; j < n; j++) {
if (isWater[i][j] == 1) {
height[i][j] = 0;
queue.offer(new int[]{i, j});
}
}
}
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int x = curr[0];
int y = curr[1];
for (int[] dir : dirs) {
int newX = x + dir[0];
int newY = y + dir[1];
if (newX >= 0 && newX < m && newY >= 0 && newY < n && height[newX][newY] == -1) {
height[newX][newY] = height[x][y] + 1;
queue.offer(new int[]{newX, newY});
}
}
}
return height;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.