PREP37 Editorial

Problem Explanation

we are given a 2D matrix of heights. There are two lakes - Red lake connected to the right and bottom border of the matrix and Blue lake connected to the left and top border of the matrix. water can flow from one cell to another only if the height of an adjacent cell(top, bottom, left and right) is less or equal to the current cell. We have to tell how many cells will have water from both the lakes.

Approach

We can use DFS to map the flow of water in the matrix. We will make a matrix for the red lake and a matrix for the blue lake. Then for the red lake we start the DFS from all the cells at right and bottom border and move to another cell if it is not visited and it’s height is not greater than the current cell. We do the same for the blue lake for every cell at the top and left borders. After that we just count the cells visited in both the matrices and output the count.