Number of Enclaves
BFS & DFS Problems DSA practice problem on Onlearn.
Difficulty: hard.
Topics: Number of Enclaved Land Cells in a Binary Matrix (Enclaves Problem), Matrices, Two-dimensional Array Traversal, Graph Traversal, Breadth-First Search, Queue, Arrays, Depth-First Search, Time Complexity, Space Complexity, edge cases, graph components, visited tracking, dfs, matrix traversal, bfs, Number of Islands / Flood Fill, Graph Traversal Utilities.
Number of Enclaves Problem Statement You are given an N x M binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4 directionally) land cell or walking off the boundary of the grid. Find the number of land cells in the grid for which we cannot walk off the boundary of the grid in any number of moves. Input Specification The input consists of a binary matrix grid of size N x M. Output Specification Return an integer representing the number of land cells from which it is impossible to walk off the boundary. Sample Test Cases Sample 1 Input: Output: Explanation: The land cells at (1, 0), (2, 1), and (2, 2) are not connected to the boundary. The land cell at (1, 2) is connected to the boundary via (0,2) if it were 1, but here it is (1,2) which is 1, so it is connected to a boundary cell (0,2) via path (1,2) (0,2). Wait, the problem is about walking off the boundary. The cells that can reach the boundary are NOT enclaves. So (1,2) cannot be an enclave. Let's re evaluate based on the provided output. The cells that cannot reach the boundary are (2,1), (2,2) and the (1,0) land cell cannot reach boundary. The example output is 3. These cells are grid[1][0], grid[2][1], grid[2][2]. The cell grid[1][2] (which is 1) is connected to grid[0][2] (if it were 1) and grid[2][2] which is a 1. The problem means if a land cell is connected to any boundary land cell, it is NOT an enclave. So, we need to count land cells that are not connected to boundary land cells. The explanation seems to be for (1,0), (2,1), (2,2). Yes, these are the three cells. The original example explanation has highlighted cells but the text doesn't specify which. I will stick to what seems logically correct for the output 3. Let's rephrase the explanation from the source: