## 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.