KatInterview

Count Landlocked Islands

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsdfsconnected-components

Last updated

Tests connected-component detection in grids with boundary constraints using BFS or DFS traversal.

You are given an m x n binary grid where each cell represents either land or water:

  • 1 represents land
  • 0 represents water

An island is a maximal group of 1-cells connected in the four cardinal directions (up, down, left, right).

A landlocked island is an island where none of its cells touch the grid boundary. In other words, no cell in the island is located on the first row, last row, first column, or last column of the grid.

Write a function that counts the number of landlocked islands in the grid.

Constraints:

  • 1 ≤ m, n ≤ 500
  • grid[i][j] is either 0 or 1
  • Two land cells belong to the same island only if they are connected horizontally or vertically (not diagonally)
  • An island touching any edge of the grid should not be counted

Examples

Example 1

Input: count_landlocked_islands([[1, 1, 1], [1, 0, 1], [1, 1, 1]])

Output: 0

Example 2

Input: count_landlocked_islands([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]])

Output: 1

Example 3

Input: count_landlocked_islands([[0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]])

Output: 3

Hints

Hint 1

Think of this as a standard island-counting problem with one extra check: track whether each island contains any boundary cell.

Hint 2

Use BFS or DFS to explore each island completely. During traversal, keep a flag that becomes true if any cell in the component is on the border.

Hint 3

Mark cells as visited when you add them to the queue (not when you remove them) to avoid processing the same cell multiple times.