-
Notifications
You must be signed in to change notification settings - Fork 6
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
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 52247b5
Automated commit rollback 1
mah-shamim cebdeef
Automated commit 2
mah-shamim fbd99fe
Automated commit rollback 2
mah-shamim ff98859
Automated commit 3
mah-shamim b7b3a41
Automated commit rollback 3
mah-shamim d9f960a
Automated commit 4
mah-shamim 92bb579
Automated commit rollback 4
mah-shamim b71a3b3
Automated commit 5
mah-shamim 498d86a
Automated commit rollback 5
mah-shamim 8599425
Automated commit 6
mah-shamim a22493b
Automated commit rollback 6
mah-shamim a74be60
Automated commit 7
mah-shamim cd8b781
Automated commit rollback 7
mah-shamim c888464
Automated commit 8
mah-shamim 9f50532
Automated commit rollback 8
mah-shamim 9d7f53f
Automated commit 9
mah-shamim d8d7207
Automated commit rollback 9
mah-shamim 4e778fa
Automated commit 10
mah-shamim 6c5ee14
Automated commit rollback 10
mah-shamim 20dcf52
Automated commit 11
mah-shamim 12f5380
Automated commit rollback 11
mah-shamim 7b5e223
Automated commit 12
mah-shamim 9bcd200
Automated commit rollback 12
mah-shamim ff8756d
Automated commit 13
mah-shamim f85de78
Automated commit rollback 13
mah-shamim 1f489fb
Automated commit 14
mah-shamim 1db08ce
Automated commit rollback 14
mah-shamim 5881d40
Automated commit 15
mah-shamim c5a0109
Automated commit rollback 15
mah-shamim a030d27
Automated commit 16
mah-shamim 66c9c96
Automated commit rollback 16
mah-shamim c949c89
Automated commit 17
mah-shamim bf58f3f
Automated commit rollback 17
mah-shamim 86a9396
Automated commit 18
mah-shamim 03fd0e4
Automated commit rollback 18
mah-shamim f0f7a64
Automated commit 19
mah-shamim 08be256
Automated commit rollback 19
mah-shamim 437bc5e
Automated commit 20
mah-shamim 878b680
Automated commit rollback 20
mah-shamim f27f2f8
Automated commit 21
mah-shamim 6322cb3
Automated commit rollback 21
mah-shamim 3206113
Automated commit 22
mah-shamim 36fd7e3
Automated commit rollback 22
mah-shamim 2b4674f
Automated commit 23
mah-shamim af1aea5
Automated commit rollback 23
mah-shamim c693c73
Automated commit 24
mah-shamim 66ef61d
Automated commit rollback 24
mah-shamim 71091d4
Automated commit 25
mah-shamim 34b3a3a
Automated commit rollback 25
mah-shamim 6f2c58c
Automated commit 26
mah-shamim 64e4bf8
Automated commit rollback 26
mah-shamim daec491
Automated commit 27
mah-shamim ad02c08
Automated commit rollback 27
mah-shamim 28e645e
Automated commit 28
mah-shamim 52ca74a
Automated commit rollback 28
mah-shamim 3a4ef21
Automated commit 29
mah-shamim 713c25f
Automated commit rollback 29
mah-shamim 1ea43a9
Automated commit 30
mah-shamim 7ca2920
Automated commit rollback 30
mah-shamim 55ff4ca
Automated commit 31
mah-shamim 42ae4b5
Automated commit rollback 31
mah-shamim ef02453
Automated commit 32
mah-shamim 898d591
Automated commit rollback 32
mah-shamim b658cc4
Automated commit 33
mah-shamim 60c828f
Automated commit rollback 33
mah-shamim 0a34691
Automated commit 34
mah-shamim 27bbd6f
Automated commit rollback 34
mah-shamim cd4170d
Automated commit 35
mah-shamim 1656410
Automated commit rollback 35
mah-shamim cb10d77
Automated commit 36
mah-shamim 835f959
Automated commit rollback 36
mah-shamim 881e3b3
Automated commit 37
mah-shamim 4e957bc
Automated commit rollback 37
mah-shamim a4c6563
Automated commit 38
mah-shamim abbc7d5
Automated commit rollback 38
mah-shamim 0d573b8
Automated commit 39
mah-shamim f09adf4
Automated commit rollback 39
mah-shamim af34ab5
Automated commit 40
mah-shamim 18512b2
Automated commit rollback 40
mah-shamim b2fe29e
Automated commit 41
mah-shamim fcc4f9a
Automated commit rollback 41
mah-shamim 92d60e1
Automated commit 42
mah-shamim 351c0ca
Automated commit rollback 42
mah-shamim ba73ac5
Automated commit 43
mah-shamim 42f26b3
Automated commit rollback 43
mah-shamim c9fe286
Automated commit 44
mah-shamim 97edc73
Automated commit rollback 44
mah-shamim 5c953a5
Automated commit 45
mah-shamim 56f7995
Automated commit rollback 45
mah-shamim 48c88a5
Automated commit 46
mah-shamim 5751aeb
Automated commit rollback 46
mah-shamim 00c64b6
Automated commit 47
mah-shamim 2191c20
Automated commit rollback 47
mah-shamim 21ee3ac
Automated commit 48
mah-shamim 23ecfe0
Automated commit rollback 48
mah-shamim 72ad563
Automated commit 49
mah-shamim 4540fd8
Automated commit rollback 49
mah-shamim 297dc03
Automated commit 50
mah-shamim 21d8236
Automated commit rollback 50
mah-shamim 040375c
#1179, #1180 leetcode problems 000407-trapping-rain-water-ii submissi…
mah-shamim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)** |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done