Count closed islands in a grid
Company: Oracle
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
## Problem
You are given an `m x n` 2D grid representing a map after flooding:
- `0` = water
- `1` = land
An **island** is a maximal 4-directionally connected component of land cells (`1`s), where connectivity is via **up, down, left, right** (not diagonals).
A **closed island** is an island that **does not touch the grid boundary** (i.e., none of its cells lie in the first/last row or first/last column). Any island that touches the boundary is **not counted**.
### Task
Return the number of **closed islands** in the grid.
### Input
- `grid`: `int[m][n]`
### Output
- `int`: the number of closed islands
### Notes / Assumptions
- Use 4-directional adjacency.
- You may assume `m, n >= 1`.
### Example
If an island is entirely surrounded by water but a land cell touches the border, it should **not** be counted as closed.
Quick Answer: This question evaluates grid traversal and connected-component detection skills, focusing on 4-directional adjacency and boundary-condition reasoning in matrix-based maps.
In a grid where 1 is land and 0 is water, count 4-directional land components that do not touch the grid boundary.
Constraints
- Use 4-directional adjacency only
- m,n >= 1 in normal inputs
Examples
Input: ([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]],)
Expected Output: 1
Input: ([[1, 1, 1], [1, 0, 1], [1, 1, 1]],)
Expected Output: 0
Input: ([[0, 0, 0], [0, 1, 0], [0, 0, 1]],)
Expected Output: 1
Hints
- DFS/BFS each land component and track whether it reaches the boundary.