# Water flow

Posted: 6 Jan, 2021

Difficulty: Hard

#### You are given a matrix 'A' having ‘N’ rows and ‘M’ columns. Each cell of the matrix represents the height of water placed in that cell. Water can flow only in four directions ( up, down, right, and left) but only to a cell having its height less than or equal to the height of the current cell.

#### The four boundaries of the matrix represent the oceans- the left and top boundary represent the Pacific ocean, and the right and bottom boundary represent the Atlantic ocean.

#### You need to find the list of coordinates from which water can flow to both the oceans. The list should be sorted in lexicographical order.

##### Input Format:

```
The first line of the input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains two space-separated positive integers ‘N’ and ‘M’ denoting the number of the rows and columns in a matrix 'A' respectively.
In the next ‘N’ lines of each test case, the ith line contains ‘M’ space-separated integers denoting the height of water.
```

##### Output Format:

```
The first line of output of each test case should contain positive integer ‘K’ denoting the total number of coordinates.
The next ‘K’ lines contain one coordinate in each line.
```

##### Note:

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

##### Constraints:

```
1 <= T <= 50
1 <= N <= 10^4
1 <= M <= 10^4
1 <= N*M <= 10^4
1 <= A[i][j] <= 10^9
Time Limit: 1 sec
```

Approach 1

- We will run two nested loops to traverse each cell of the matrix.
- For each cell, we perform DFS in which we go to all adjacent neighbours having their height lower than the current cell.
- We take two boolean variables to mark the reachability of that cell to the ocean. If we somehow reach any of the ocean we mark the corresponding boolean variable to be true.
- In the end, if both of the boolean variables are true then it means this cell can reach both of the oceans hence we include this cell in our answer.

Approach 2

- Every cell wants to reach the ocean so instead of checking for every cell, we can check how many cells are there to which ocean can reach.
- For this purpose, we will use multi-source bfs for each ocean. In multi-source bfs we insert all the cells lying on the boundary of that ocean in the queue. Then we perform our normal bfs by adding all adjacent elements of the current element having their height greater than equal to the head of bfs. We mark all the cells which are visited in this process.
- We perform multi-source bfs for both oceans separately and prepare two matrices ( one for each ocean) to mark visited cells. Now the cell which is marked in both matrices means this cell can reach both the oceans and hence it should be included in our answer.