Skills101
← All coding problems

Pacific Atlantic Water Flow

mediumGraphs+20 XPTime limit 2s

An island is a grid of heights. The Pacific ocean touches the top and left edges; the Atlantic touches the bottom and right edges. Rain water flows from a cell to a neighbour (up/down/left/right) whose height is less than or equal, and from edge cells into the ocean next to them. Find every cell from which water can reach both oceans.

Input:

  • line 1: r c
  • next r lines: c heights each

Output:

  • line 1: the number of cells k
  • next k lines: row col (0-based), sorted by row, then by column

Constraints: 1 ≤ r, c ≤ 200, 0 ≤ height ≤ 10⁵.

Think about it: searching from every cell is slow. Reverse the flow instead: start from each ocean's edge cells and climb uphill (to neighbours with height ≥). The answer is the intersection of the two reachable sets.

Sample input 1

5 5
1 2 2 3 5
3 2 3 4 4
2 4 5 3 1
6 7 1 4 5
5 1 1 2 4

Sample output 1

7
0 4
1 3
1 4
2 2
3 0
3 1
4 0

Sample input 2

1 1
1

Sample output 2

1
0 0

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.