Pacific Atlantic Water Flow

Medium

Pacific Atlantic Water Flow

Problem Description

Given a 2D matrix

matrix
representing an island and the ocean, find the number of cells with water flowing from the Pacific Ocean to the Atlantic Ocean.

Each cell is marked as either the ocean (

0
), the Pacific Ocean (
1
), the Atlantic Ocean (
2
), or the land (
3
).

For water to flow from the Pacific Ocean to the Atlantic Ocean, cells must be connected horizontally or vertically. We are interested in counting the number of such cells.

Rules and Constraints

  • The input
    matrix
    is a 2D array of integers, where each integer is either
    0
    ,
    1
    ,
    2
    , or
    3
    .
  • The input
    matrix
    is a rectangle, i.e., each row has the same number of columns, and there is at least one row.
  • The Pacific Ocean is marked by
    1
    , and the Atlantic Ocean is marked by
    2
    .
  • The land is marked by
    3
    .
  • Time complexity must be O(m * n), where
    m
    is the number of rows and
    n
    is the number of columns in the matrix.
  • Space complexity must also be O(m * n), as extra space may be needed to store the result.

Task

Write a function that takes the input

matrix
and returns the number of cells with water flowing from the Pacific Ocean to the Atlantic Ocean.

Example

Input: {"input_data":[1,2,3]} Output: [1,2,3]

CompaniesGoogleMetaAmazon
JavaScript

Login to write code

Solve problems, verify your skills, and earn XP.