#K67322. Water Flow to the Edge
Water Flow to the Edge
Water Flow to the Edge
In this problem, you are given a grid representing the heights of a terrain and a list of water sources. Water flows from a cell to an adjacent cell (up, down, left, or right) if and only if the adjacent cell's height is lower than or equal to the current cell's height.
Your task is to determine whether there exists a water source from which water can reach any cell on the border (edge) of the grid. Formally, given an \( n \times m \) grid \( G \) and a set of water sources, determine if there exists at least one water source for which a path exists that leads to any cell on the boundary of the grid.
Note: The water can only flow from a cell \( (i, j) \) to a neighboring cell \( (i', j') \) if \( G(i', j') \leq G(i, j) \). The grid indices are 0-indexed.
Hint: You can use a breadth-first search (BFS) or depth-first search (DFS) algorithm to explore possible paths from each water source.
inputFormat
The input is given in the following format:
- Two integers \( n \) and \( m \) separated by a space, representing the number of rows and columns of the grid.
- Next \( n \) lines, each containing \( m \) space-separated integers, representing the heights of the cells in the grid.
- An integer \( k \) which denotes the number of water sources.
- Then \( k \) lines follow, each containing two space-separated integers \( r \) and \( c \) (0-indexed), indicating the row and column of a water source.
outputFormat
Output a single line containing either "YES" if water can flow from at least one water source to any edge of the grid, or "NO" otherwise.
## sample3 3
5 4 3
6 1 8
7 8 9
2
0 1
2 1
YES