Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

000407 trapping rain water ii #1181

Merged
merged 101 commits into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
16f14d8
Automated commit 1
mah-shamim Jan 19, 2025
52247b5
Automated commit rollback 1
mah-shamim Jan 19, 2025
cebdeef
Automated commit 2
mah-shamim Jan 19, 2025
fbd99fe
Automated commit rollback 2
mah-shamim Jan 19, 2025
ff98859
Automated commit 3
mah-shamim Jan 19, 2025
b7b3a41
Automated commit rollback 3
mah-shamim Jan 19, 2025
d9f960a
Automated commit 4
mah-shamim Jan 19, 2025
92bb579
Automated commit rollback 4
mah-shamim Jan 19, 2025
b71a3b3
Automated commit 5
mah-shamim Jan 19, 2025
498d86a
Automated commit rollback 5
mah-shamim Jan 19, 2025
8599425
Automated commit 6
mah-shamim Jan 19, 2025
a22493b
Automated commit rollback 6
mah-shamim Jan 19, 2025
a74be60
Automated commit 7
mah-shamim Jan 19, 2025
cd8b781
Automated commit rollback 7
mah-shamim Jan 19, 2025
c888464
Automated commit 8
mah-shamim Jan 19, 2025
9f50532
Automated commit rollback 8
mah-shamim Jan 19, 2025
9d7f53f
Automated commit 9
mah-shamim Jan 19, 2025
d8d7207
Automated commit rollback 9
mah-shamim Jan 19, 2025
4e778fa
Automated commit 10
mah-shamim Jan 19, 2025
6c5ee14
Automated commit rollback 10
mah-shamim Jan 19, 2025
20dcf52
Automated commit 11
mah-shamim Jan 19, 2025
12f5380
Automated commit rollback 11
mah-shamim Jan 19, 2025
7b5e223
Automated commit 12
mah-shamim Jan 19, 2025
9bcd200
Automated commit rollback 12
mah-shamim Jan 19, 2025
ff8756d
Automated commit 13
mah-shamim Jan 19, 2025
f85de78
Automated commit rollback 13
mah-shamim Jan 19, 2025
1f489fb
Automated commit 14
mah-shamim Jan 19, 2025
1db08ce
Automated commit rollback 14
mah-shamim Jan 19, 2025
5881d40
Automated commit 15
mah-shamim Jan 19, 2025
c5a0109
Automated commit rollback 15
mah-shamim Jan 19, 2025
a030d27
Automated commit 16
mah-shamim Jan 19, 2025
66c9c96
Automated commit rollback 16
mah-shamim Jan 19, 2025
c949c89
Automated commit 17
mah-shamim Jan 19, 2025
bf58f3f
Automated commit rollback 17
mah-shamim Jan 19, 2025
86a9396
Automated commit 18
mah-shamim Jan 19, 2025
03fd0e4
Automated commit rollback 18
mah-shamim Jan 19, 2025
f0f7a64
Automated commit 19
mah-shamim Jan 19, 2025
08be256
Automated commit rollback 19
mah-shamim Jan 19, 2025
437bc5e
Automated commit 20
mah-shamim Jan 19, 2025
878b680
Automated commit rollback 20
mah-shamim Jan 19, 2025
f27f2f8
Automated commit 21
mah-shamim Jan 19, 2025
6322cb3
Automated commit rollback 21
mah-shamim Jan 19, 2025
3206113
Automated commit 22
mah-shamim Jan 19, 2025
36fd7e3
Automated commit rollback 22
mah-shamim Jan 19, 2025
2b4674f
Automated commit 23
mah-shamim Jan 19, 2025
af1aea5
Automated commit rollback 23
mah-shamim Jan 19, 2025
c693c73
Automated commit 24
mah-shamim Jan 19, 2025
66ef61d
Automated commit rollback 24
mah-shamim Jan 19, 2025
71091d4
Automated commit 25
mah-shamim Jan 19, 2025
34b3a3a
Automated commit rollback 25
mah-shamim Jan 19, 2025
6f2c58c
Automated commit 26
mah-shamim Jan 19, 2025
64e4bf8
Automated commit rollback 26
mah-shamim Jan 19, 2025
daec491
Automated commit 27
mah-shamim Jan 19, 2025
ad02c08
Automated commit rollback 27
mah-shamim Jan 19, 2025
28e645e
Automated commit 28
mah-shamim Jan 19, 2025
52ca74a
Automated commit rollback 28
mah-shamim Jan 19, 2025
3a4ef21
Automated commit 29
mah-shamim Jan 19, 2025
713c25f
Automated commit rollback 29
mah-shamim Jan 19, 2025
1ea43a9
Automated commit 30
mah-shamim Jan 19, 2025
7ca2920
Automated commit rollback 30
mah-shamim Jan 19, 2025
55ff4ca
Automated commit 31
mah-shamim Jan 19, 2025
42ae4b5
Automated commit rollback 31
mah-shamim Jan 19, 2025
ef02453
Automated commit 32
mah-shamim Jan 19, 2025
898d591
Automated commit rollback 32
mah-shamim Jan 19, 2025
b658cc4
Automated commit 33
mah-shamim Jan 19, 2025
60c828f
Automated commit rollback 33
mah-shamim Jan 19, 2025
0a34691
Automated commit 34
mah-shamim Jan 19, 2025
27bbd6f
Automated commit rollback 34
mah-shamim Jan 19, 2025
cd4170d
Automated commit 35
mah-shamim Jan 19, 2025
1656410
Automated commit rollback 35
mah-shamim Jan 19, 2025
cb10d77
Automated commit 36
mah-shamim Jan 19, 2025
835f959
Automated commit rollback 36
mah-shamim Jan 19, 2025
881e3b3
Automated commit 37
mah-shamim Jan 19, 2025
4e957bc
Automated commit rollback 37
mah-shamim Jan 19, 2025
a4c6563
Automated commit 38
mah-shamim Jan 19, 2025
abbc7d5
Automated commit rollback 38
mah-shamim Jan 19, 2025
0d573b8
Automated commit 39
mah-shamim Jan 19, 2025
f09adf4
Automated commit rollback 39
mah-shamim Jan 19, 2025
af34ab5
Automated commit 40
mah-shamim Jan 19, 2025
18512b2
Automated commit rollback 40
mah-shamim Jan 19, 2025
b2fe29e
Automated commit 41
mah-shamim Jan 19, 2025
fcc4f9a
Automated commit rollback 41
mah-shamim Jan 19, 2025
92d60e1
Automated commit 42
mah-shamim Jan 19, 2025
351c0ca
Automated commit rollback 42
mah-shamim Jan 19, 2025
ba73ac5
Automated commit 43
mah-shamim Jan 19, 2025
42f26b3
Automated commit rollback 43
mah-shamim Jan 19, 2025
c9fe286
Automated commit 44
mah-shamim Jan 19, 2025
97edc73
Automated commit rollback 44
mah-shamim Jan 19, 2025
5c953a5
Automated commit 45
mah-shamim Jan 19, 2025
56f7995
Automated commit rollback 45
mah-shamim Jan 19, 2025
48c88a5
Automated commit 46
mah-shamim Jan 19, 2025
5751aeb
Automated commit rollback 46
mah-shamim Jan 19, 2025
00c64b6
Automated commit 47
mah-shamim Jan 19, 2025
2191c20
Automated commit rollback 47
mah-shamim Jan 19, 2025
21ee3ac
Automated commit 48
mah-shamim Jan 19, 2025
23ecfe0
Automated commit rollback 48
mah-shamim Jan 19, 2025
72ad563
Automated commit 49
mah-shamim Jan 19, 2025
4540fd8
Automated commit rollback 49
mah-shamim Jan 19, 2025
297dc03
Automated commit 50
mah-shamim Jan 19, 2025
21d8236
Automated commit rollback 50
mah-shamim Jan 19, 2025
040375c
#1179, #1180 leetcode problems 000407-trapping-rain-water-ii submissi…
mah-shamim Jan 19, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 175 additions & 0 deletions algorithms/000407-trapping-rain-water-ii/README.md
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
407\. Trapping Rain Water II

**Difficulty:** Hard

**Topics:** `Array`, `Breadth-First Search`, `Heap (Priority Queue)`, `Matrix`

Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return _the volume of water it can trap after raining_.

**Example 1:**

![trap1-3d](https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg)

- **Input:** heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
- **Output:** 4
- **Explanation:** After the rain, water is trapped between the blocks.
We have two small ponds 1 and 3 units trapped.
The total volume of water trapped is 4.

**Example 2:**

![trap2-3d](https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg)

- **Input:** heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
- **Output:** 10



**Constraints:**

- `m == heightMap.length`
- `n == heightMap[i].length`
- `1 <= m, n <= 200`
- <code>0 <= heightMap[i][j] <= 2 * 10<sup>4</sup></code>


**Solution:**

The "Trapping Rain Water II" problem is a challenging computational problem that requires us to compute the volume of water trapped after raining on a 2D elevation map represented as a matrix. This problem extends the classic "Trapping Rain Water" problem to two dimensions, making the solution more complex due to the need to consider water flow in all directions.


## **Key Points**
1. **Matrix Representation**: The `heightMap` matrix contains the elevation of each cell.
2. **Boundary Constraints**: Water cannot flow out of the boundary cells.
3. **Heap Data Structure**: A min-heap (priority queue) is used to simulate the water levels dynamically.
4. **Visited Matrix**: To prevent revisiting cells, we track visited nodes.


## **Approach**
The solution leverages a **Breadth-First Search (BFS)** approach, guided by a **priority queue (min-heap)**:
1. Add all boundary cells to the min-heap and mark them as visited.
2. Process cells in increasing height order:
- For each cell, attempt to "trap" water in its neighbors.
- Push neighboring cells into the heap with updated height values.
3. Accumulate the trapped water volume based on the height difference between the current cell and its neighbors.


## **Plan**
1. **Initialization**:
- Define matrix dimensions and edge cases.
- Initialize a min-heap for boundary cells.
- Create a `visited` matrix.

2. **Insert Boundary Cells**:
- Push all boundary cells into the heap with their height values.
- Mark them as visited.

3. **BFS Traversal**:
- While the heap is not empty, extract the cell with the smallest height.
- Check all its neighbors and calculate trapped water:
- If the neighbor is lower, the height difference contributes to trapped water.
- Update the neighbor's height to the current cell's height if higher.
- Push the neighbor into the heap and mark it visited.

4. **Return Result**:
- The accumulated water volume represents the trapped rainwater.

Let's implement this solution in PHP: **[407. Trapping Rain Water II](https://github.com/mah-shamim/leet-code-in-php/tree/main/algorithms/000407-trapping-rain-water-ii/solution.php)**

```php
<?php
/**
* @param Integer[][] $heightMap
* @return Integer
*/
function trapRainWater($heightMap) {
...
...
...
/**
* go to ./solution.php
*/
}

// Example Usage
$heightMap1 = [[1, 4, 3, 1, 3, 2], [3, 2, 1, 3, 2, 4], [2, 3, 3, 2, 3, 1]];
$heightMap2 = [[3, 3, 3, 3, 3], [3, 2, 2, 2, 3], [3, 2, 1, 2, 3], [3, 2, 2, 2, 3], [3, 3, 3, 3, 3]];

echo trapRainWater($heightMap1) . "\n"; // Output: 4
echo trapRainWater($heightMap2) . "\n"; // Output: 10
?>
```

### Explanation:

1. **Boundary Initialization**:
- All boundary cells are added to the heap to form the outer walls of the container.

2. **Heap Extraction**:
- Extract the cell with the lowest height, ensuring that water flows only outward, not inward.

3. **Neighbor Exploration**:
- For each neighbor:
- Check if it’s within bounds and unvisited.
- Calculate the water trapped as `max(0, currentHeight - neighborHeight)`.
- Push the updated neighbor height into the heap.

4. **Accumulate Water**:
- Add the trapped water for each neighbor to the total.


## **Example Walkthrough**
### Input:
```php
$heightMap = [
[1, 4, 3, 1, 3, 2],
[3, 2, 1, 3, 2, 4],
[2, 3, 3, 2, 3, 1]
];
```
### Steps:
1. **Boundary Cells**:
- Push cells from the boundary into the heap with their heights:
- Example: `(0, 0, 1)`, `(0, 1, 4)`, etc.

2. **Heap Traversal**:
- Extract cell `(0, 0, 1)` (lowest height).
- Check neighbors, calculate water trapped:
- For neighbor `(1, 0)`: Water trapped = `max(0, 1 - 3) = 0`.

3. **Trapped Water**:
- Continue processing until all cells are visited:
- Total trapped water = `4`.


## **Time Complexity**
1. **Heap Operations**:
- Each cell is pushed and popped from the heap once: `O(m * n * log(m * n))`.

2. **Neighbor Iteration**:
- Each cell has up to 4 neighbors: `O(m * n)`.

### **Total Complexity**:
**`O(m * n * log(m * n))`**


## **Output for Example**
```php
$heightMap = [
[1, 4, 3, 1, 3, 2],
[3, 2, 1, 3, 2, 4],
[2, 3, 3, 2, 3, 1]
];
echo trapRainWater($heightMap); // Output: 4
```

The "Trapping Rain Water II" problem demonstrates the power of advanced data structures like priority queues combined with BFS. By simulating the flow of water in a 2D elevation map, we can efficiently compute the total trapped water. This solution is optimal for handling large matrices due to its logarithmic heap operations.

**Contact Links**

If you found this series helpful, please consider giving the **[repository](https://github.com/mah-shamim/leet-code-in-php)** a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
93 changes: 93 additions & 0 deletions algorithms/000407-trapping-rain-water-ii/solution.php
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

class Solution {

/**
* @param Integer[][] $heightMap
* @return Integer
*/
function trapRainWater($heightMap) {
$m = count($heightMap);
$n = count($heightMap[0]);

if ($m < 3 || $n < 3) {
return 0;
}

$directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
$minHeap = new SplPriorityQueue();
$visited = array_fill(0, $m, array_fill(0, $n, false));

// Add the boundary cells to the priority queue
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($i == 0 || $i == $m - 1 || $j == 0 || $j == $n - 1) {
$minHeap->insert([$i, $j, $heightMap[$i][$j]], -$heightMap[$i][$j]);
$visited[$i][$j] = true;
}
}
}

$waterTrapped = 0;

while (!$minHeap->isEmpty()) {
list($x, $y, $h) = $minHeap->extract();
foreach ($directions as $direction) {
$nx = $x + $direction[0];
$ny = $y + $direction[1];

if ($nx >= 0 && $nx < $m && $ny >= 0 && $ny < $n && !$visited[$nx][$ny]) {
$visited[$nx][$ny] = true;
$waterTrapped += max(0, $h - $heightMap[$nx][$ny]);
$minHeap->insert([$nx, $ny, max($h, $heightMap[$nx][$ny])], -max($h, $heightMap[$nx][$ny]));
}
}
}

return $waterTrapped;
}
}
/**
* @param Integer[][] $heightMap
* @return Integer
*/
function trapRainWater($heightMap) {
$m = count($heightMap);
$n = count($heightMap[0]);

if ($m < 3 || $n < 3) {
return 0;
}

$directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];
$minHeap = new SplPriorityQueue();
$visited = array_fill(0, $m, array_fill(0, $n, false));

// Add the boundary cells to the priority queue
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($i == 0 || $i == $m - 1 || $j == 0 || $j == $n - 1) {
$minHeap->insert([$i, $j, $heightMap[$i][$j]], -$heightMap[$i][$j]);
$visited[$i][$j] = true;
}
}
}

$waterTrapped = 0;

while (!$minHeap->isEmpty()) {
list($x, $y, $h) = $minHeap->extract();
foreach ($directions as $direction) {
$nx = $x + $direction[0];
$ny = $y + $direction[1];

if ($nx >= 0 && $nx < $m && $ny >= 0 && $ny < $n && !$visited[$nx][$ny]) {
$visited[$nx][$ny] = true;
$waterTrapped += max(0, $h - $heightMap[$nx][$ny]);
$minHeap->insert([$nx, $ny, max($h, $heightMap[$nx][$ny])], -max($h, $heightMap[$nx][$ny]));
}
}
}

return $waterTrapped;
}