Trapping Rain Water
Given an M * N matrix, where the value at any cell denotes the height of that cell in a 2-D elevation map. You need to find the volume of water that can be trapped within it.
For a matrix =
[ 5, 5, 5 ]
[ 5, 2, 3 ]
[ 6, 9, 8 ]
2-D elevation map will look like this
After the rain, a total of 1 unit volume of water gets trapped, and this 2-D elevation map will look like this
Input Format:
The first line contains a single integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated integers ‘M’ and ‘N’ denoting the number of rows and columns in the matrix.
The next ‘M’ lines contain ‘N’ space-separated integers denoting the height of each cell.
Output Format:
For each test case, print a single integer denoting the volume of water that can be trapped.
Print the output of each test case in a separated line.
Note:
You don't need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= M,N <= 100
1 <= matrix[i][j] <= 10^3
Where ‘T’ is the number of test cases, ‘M’ and ‘N’ are the dimensions of the given matrix.
Matrix[i][j] is the height of the cell at the ‘i-th’ row and ‘j-th’ column.
Time Limit: 1 sec.
CodingNinjas
author
2y
1. Create two array left and right of size n. create a variable max_ = INT_MIN.
2. Run one loop from start to end. In each iteration update max_ as max_ = max(max_, arr[i]) and also assign left[i] = ma...read more
CodingNinjas
author
2y
Priority Queue Implementation.
Approach: The border cells can never hold water as water will always flow out from there. So we will assume all the border cells as our boundary.
Now the water that can b...read more
Help your peers!
Add answer anonymously...
Top ION Group Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app