Grokking Graph Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Number of Enclaves (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell, return the number of land cells in grid from which you can't reach to the boundary in any number of moves.

In a single move, you can walk from one cell to any cell, which is 4-directionally adjacent to the current cell.

Examples

Example 1:

  • Input: grid =
[[0, 0, 0, 1],
 [1, 0, 1, 0],
 [0, 1, 1, 0],
 [0, 0, 0, 0]]
  • Output: 3
  • Justification: The three land cells in the center, which are at (1, 2), (2, 1), and (2, 2) positions, are surrounded by sea cells and cannot reach the boundary.

Examples

Example 1:

  • Input: grid =
[[0, 0, 0, 1],
[1, 0, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]]
  • Output: 3
  • Justification: The three land cells in the center are surrounded by sea cells and cannot reach the boundary.

Example 2:

  • Input: grid =
[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]]
  • Output: 0
  • Justification: All land cells can connect to the edge either directly or through other land cells.

Example 3:

  • Input: grid =
[[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0]]
  • Output: 8
  • Justification: The eight land cells in the middle are surrounded by sea cells and cannot reach the boundary.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • grid[i][j] is either 0 or 1.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible