TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1624 702
Задача: 407. Trapping Rain Water II
Сложность: hard

Задав целочисленную матрицу heightMap размером m x n, представляющую высоту каждой ячейки на двумерной карте рельефа, верните объем воды, который она может задержать после дождя.

Пример:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4


👨‍💻 Алгоритм:

1⃣Используйте приоритетную очередь для хранения всех ячеек по периметру матрицы.

2⃣Постепенно извлекайте ячейки из очереди, рассматривая их соседей. Если соседняя ячейка ниже текущей, добавьте разницу в высоте к общему объему воды и обновите её высоту.

3⃣Повторите процесс, пока все ячейки не будут обработаны.

😎 Решение:
import java.util.PriorityQueue;

public class Solution {
public int trapRainWater(int[][] heightMap) {
if (heightMap.length == 0 || heightMap[0].length == 0) return 0;
int m = heightMap.length, n = heightMap[0].length;
boolean[][] visited = new boolean[m][n];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
for (int i = 0; i < m; i++) {
for (int j : new int[]{0, n-1}) {
pq.offer(new int[]{heightMap[i][j], i, j});
visited[i][j] = true;
}
}
for (int j = 0; j < n; j++) {
for (int i : new int[]{0, m-1}) {
pq.offer(new int[]{heightMap[i][j], i, j});
visited[i][j] = true;
}
}
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int water = 0;
while (!pq.isEmpty()) {
int[] cell = pq.poll();
for (int[] dir : directions) {
int nx = cell[1] + dir[0], ny = cell[2] + dir[1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[nx][ny]) {
visited[nx][ny] = true;
water += Math.max(0, cell[0] - heightMap[nx][ny]);
pq.offer(new int[]{Math.max(cell[0], heightMap[nx][ny]), nx, ny});
}
}
}
return water;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 16, 2026Задача: 735. Asteroid Collision Сложность: medium Нам дан массив asteroids, состоящий из ц…
  2. Oct 16, 2026Post #2300
  3. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
  4. Oct 14, 2026Задача: 1332. Remove Palindromic Subsequences Сложность: easy Вам дана строка s, состоящая…
  5. Oct 13, 2026Задача: 1120. Maximum Average Subtree Сложность: medium Дан корень бинарного дерева. Верни…
  6. Oct 12, 2026Задача: 1413. Minimum Value to Get Positive Step by Step Sum Сложность: easy Дан массив це…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →