Count Landlocked Islands
Trees & GraphsAuto-graded · 19 test casesLast 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:
1represents land0represents 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 ≤ 500grid[i][j]is either0or1- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a variant of connected-component counting with an additional constraint: we only count components that are entirely interior to the grid.
The solution uses breadth-first search (BFS) to identify and explore each island:
- Iterate through every cell in the grid
- When an unvisited land cell is found, start a BFS to explore the entire island
- During the BFS traversal, maintain a boolean flag tracking whether any cell in the island touches the grid boundary
- After fully exploring the island, increment the count only if the flag indicates no boundary contact
The key insight is that each island is either entirely landlocked or not—a single boundary cell disqualifies the entire connected component. We must explore the full component before deciding whether to count it.
Why This Works
- Complete exploration: BFS from an unvisited land cell reaches every cell that is 4-connected to it, which is exactly the definition of an island
- No double-counting: Each cell is marked as visited when added to the queue, ensuring each island is explored exactly once
- Accurate boundary detection: The flag is checked both for the starting cell and every cell discovered during traversal, so any boundary contact is detected
- Correct counting: We increment the counter once per component, only when that component has no boundary cells
An important detail: do not terminate the BFS early once a boundary cell is found. All cells in the component must be marked as visited, otherwise the outer loop might later encounter an unvisited cell from the same island and incorrectly treat it as a new component.
Complexity
Time complexity: O(m × n) where m and n are the grid dimensions. Each cell is visited and marked at most once, and each cell examines its 4 neighbors, giving linear total work.
Space complexity: O(m × n) for the visited matrix and the BFS queue. In the worst case (all land cells), the queue could hold all cells, though typical BFS frontiers are much smaller.
Solution
from collections import deque
from typing import List
def count_landlocked_islands(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
seen = [[False] * n for _ in range(m)]
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
count = 0
for r in range(m):
for c in range(n):
if grid[r][c] != 1 or seen[r][c]:
continue
seen[r][c] = True
queue = deque([(r, c)])
touches_boundary = r == 0 or r == m - 1 or c == 0 or c == n - 1
while queue:
cr, cc = queue.popleft()
for dr, dc in directions:
nr, nc = cr + dr, cc + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
queue.append((nr, nc))
if nr == 0 or nr == m - 1 or nc == 0 or nc == n - 1:
touches_boundary = True
if not touches_boundary:
count += 1
return count