Introduction
What do you mean by a matrix? A matrix is a two-dimensional structure identified by two indices, one for rows and another for columns. Every matrix is a two-dimensional array but not vice versa.
Trapping rainwater is a famous and routine question asked in interviews with many companies like Google, Amazon, Samsung, Adobe, etc. This particular problem we will be heading to is the topic matrix. The matrix will contain the height of each cell that can hold the rainwater, and we have to return the total volume of water it can trap after rain.
Let’s move to our problem statement for better understanding so that you can think of the appropriate approach to solve the problem.
Also check out Data Structures
Problem Statement
So the problem statement is pretty simple, we are given an m x n matrix of positive integers where each element of the matrix represents the height of the bars; we aim to find the total volume of water trapped in the matrix after rain.
Let’s understand the idea of how to solve this problem through an example.
This is like a container, and the water-filled in the container will be till the minimum boundary.
So in this container, first, I will be processing the outside boundaries because everything will be stored inside these boundaries, and slowly, I will push in the boundary.
After visiting the boundary, we can see that the minimum value we are getting from here is ‘1’.
After visiting ‘1’, we will reduce the boundary and include ‘13’ into the boundary.
The minimum boundary value is ‘12’ and updates the minimum value from ‘1’ to ‘12’.
We will push the boundary by checking the adjacent of each boundary having a value as ‘12’. If the adjacent ‘12’ is already inside the boundary, it will do nothing; otherwise, add the boundary if the boundary value is greater than ‘12’.
If the adjacent boundary value is less than ‘12’, then water will be filled inside that boundary. The amount of water-filled will be the minimum value of boundary - value of adjacent boundary(12-10=2).
The adjacent boundary of ‘10’ left outside is also less than ‘12’, i.e., ‘8’. So the amount of water filled will be 12 - 8 = 4.
The adjacent boundary of ‘8’ left outside the boundary is also less than ‘12’, i.e., ‘4’. So the amount of water filled will be 12 - 4 = 8.
The total amount of rainwater trapped will be 2+4+8=14
Now the minimum boundary value will get updated to ‘13’ and check for the adjacent boundaries that are unvisited or visited.
We can see that all the adjacent boundaries of ‘13’ are visited. So will get the total volume of rainwater trapped in between the bars after rain.