my dsa gallery
Graph / MatrixBoundary DFS / Flood Fill

Number of Enclaves

Problem link: https://leetcode.com/problems/number-of-enclaves/

Problem Statement

You are given an m x n binary matrix grid, where 0 represents sea and 1 represents land. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid. Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.

Input

An m x n binary matrix grid.

Output

An integer representing the count of trapped land cells.

Example

Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3

Explanation

The '1' at (1,0) is on the boundary. We 'sink' it. The cluster of '1's at (1,2), (2,1), and (2,2) cannot reach any edge, so they are enclaves.

Brute Force

Intuition

For every land cell, perform a DFS to see if it can reach the boundary.

Approach

  1. Iterate through all cells.
  2. If cell is '1', run DFS.
  3. If DFS never touches an edge, increment count.
Time: O((M*N)^2)Space: O(M*N)

Optimal Solution

Intuition

Reverse the logic: Sink all land that CAN reach the boundary. What remains must be an enclave.

Approach

  1. Loop through the boundary cells of the grid.
  2. If a cell is '1', use DFS to turn it and all connected land cells into '0'.
  3. After the boundary DFS is done, loop through the entire grid and count the remaining '1's.

Code (Java)

Time: O(M * N)Space: O(M * N)

Complexity Analysis

Each cell is visited at most twice. Space is for the recursion stack.

Quick Revision (Brute Force)

  • DFS from every land cell
  • O(M*N)^2

Quick Revision (Optimal)

  • Boundary DFS to sink reachable land
  • Count remaining 1s
  • O(M*N)

Study Photos

Upload screenshots/notes for this specific problem.

Drag & drop or click to select
Drop an image anywhere in this box to upload.
No photos uploaded till now.

Comments

Stored in D1. Login required.
  • BFS : class Solution { public int numEnclaves(int[][] grid) { int m = grid.length; int n = grid[0].length; Queue<int[]> q = new LinkedList<>(); for(int i=0;i<m;i++){ if(grid[i][0] == 1){ q.offer(new int[]{i,0}); grid[i][0] = -1; } if(grid[i][n-1] == 1){ q.offer(new int[]{i,n-1}); grid[i][n-1] = -1; } } for(int j=0;j<n;j++){ if(grid[0][j] == 1){ q.offer(new int[]{0,j}); grid[0][j] = -1; } if(grid[m-1][j] == 1){ q.offer(new int[]{m-1,j}); grid[m-1][j] = -1; } } int[][] dir = {{0,-1},{0,1},{-1,0},{1,0}}; while(!q.isEmpty()){ int[] current = q.poll(); int row = current[0]; int col = current[1]; for(int[] d : dir){ int newRow = d[0] + row; int newCol = d[1] + col; if(newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && grid[newRow][newCol] == 1){ grid[newRow][newCol] = -1; q.offer(new int[]{newRow,newCol}); } } } int ans = 0; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(grid[i][j] == 1){ ans++; } } } return ans; } }
    2026-04-19T06:05:19.244Z