Skip to content
Related Articles
Open in App
Not now

Related Articles

Number of land cells for which we cannot walk off the boundary of Grid

Improve Article
Save Article
  • Last Updated : 08 Dec, 2022
Improve Article
Save Article

Given an N x N 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 that is left, right, up, and down) 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.

Examples:

Input: grid[][] = {{0, 0, 0, 0}, {1, 0, 1, 0}, {0, 1, 1, 0},  {0, 0, 0, 0}}
Output: 3
Explanation: For the land cells at positions (1, 2), (2, 1) and (2, 2)
we cannot walk off the boundary.

Input:
grid [][]= {{0, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}};
Output: 0

Approach: The problem can be solved based on the following idea:

First mark the land cells which are connected by the boundary and then count the total number of cells in the islands that are not marked.

Follow the steps below to solve the problem:

  • Take a visited array of size N * N, each initialized with 0
  • Do a DFS traversal on each boundary of the matrix i.e, the first row, first column, last row, and last column. 
    • During the traversal, check whether there is any 1 that is attached to the boundary or not. 
    • If attached mark that cell in the visited array as 1 and continue the dfs for its adjacent cells.
  • Initialize a counter with zero and run a for loop on each cell of the given matrix and the visited matrix. 
    • If for any cell, that cell is not visited and the grid contains one then such cell will contribute to the answer and increase the counter by one.
  • Print the counter value.

Below is the implementation of the above approach.

C++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to run DFS on matrix
void dfs(vector<vector<int> >& grid,
         vector<vector<int> >& visited, int row, int col)
{
    if (row >= 0 && row < grid.size() && col >= 0
        && col < grid[0].size() && grid[row][col] == 1
        && !visited[row][col]) {
        visited[row][col] = 1;
        dfs(grid, visited, row + 1, col);
        dfs(grid, visited, row - 1, col);
        dfs(grid, visited, row, col + 1);
        dfs(grid, visited, row, col - 1);
    }
}

// Function to find the number of cells
// from which we cannot walk out of boundary
int numberOfEnclaves(vector<vector<int> >& grid)
{
    int n = grid.size();
    int m = grid[0].size();
    vector<vector<int> > visited(n, vector<int>(m, 0));

    // If statement to reduce
    // the no of calls for the dfs
    for (int i = 0; i < n; i++) {
        // First column
        if (!visited[i][0] && grid[i][0] == 1) {
            dfs(grid, visited, i, 0);
        }
        // Last column
        if (!visited[i][m - 1] && grid[i][m - 1] == 1) {
            dfs(grid, visited, i, m - 1);
        }
    }

    for (int j = 0; j < m; j++) {
        // First row
        if (!visited[0][j] && grid[0][j] == 1) {
            dfs(grid, visited, 0, j);
        }
        // Last row
        if (!visited[n - 1][j] && grid[n - 1][j] == 1) {
            dfs(grid, visited, n - 1, j);
        }
    }

    int count = 0;

    // Loop to count the number of cells
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (!visited[i][j] && grid[i][j] == 1)
                count++;
        }
    }

    // Return the total count of cells
    return count;
}

// Driver code
int main()
{
    int N = 4;
    vector<vector<int> > graph(N, vector<int>(N, 0));
    graph = { { 0, 0, 0, 0 },
              { 1, 0, 1, 0 },
              { 0, 1, 1, 0 },
              { 0, 0, 0, 0 } };

    // Function call
    cout << numberOfEnclaves(graph);
    return 0;
}

Java

// java implementation
import java.io.*;

class GFG {

  // Function to run DFS on matrix
  public static void dfs(int[][] grid, int[][] visited,
                         int row, int col)
  {
    if (row >= 0 && row < grid.length && col >= 0
        && col < grid[0].length && grid[row][col] == 1
        && visited[row][col] == 0) {
      visited[row][col] = 1;
      dfs(grid, visited, row + 1, col);
      dfs(grid, visited, row - 1, col);
      dfs(grid, visited, row, col + 1);
      dfs(grid, visited, row, col - 1);
    }
  }

  // Function to find the number of cells
  // from which we cannot walk out off boundary
  public static int numberOfEnclaves(int[][] grid)
  {
    int n = grid.length;
    int m = grid[0].length;
    int[][] visited = new int[n][m];

    // If statement to reduce
    // the no of calls for the dfs
    for (int i = 0; i < n; i++) {
      // First column
      if (visited[i][0] == 0 && grid[i][0] == 1) {
        dfs(grid, visited, i, 0);
      }
      // Last column
      if (visited[i][m - 1] == 0
          && grid[i][m - 1] == 1) {
        dfs(grid, visited, i, m - 1);
      }
    }

    for (int j = 0; j < m; j++) {
      // First row
      if (visited[0][j] == 0 && grid[0][j] == 1) {
        dfs(grid, visited, 0, j);
      }
      // Last row
      if (visited[n - 1][j] == 0
          && grid[n - 1][j] == 1) {
        dfs(grid, visited, n - 1, j);
      }
    }

    int count = 0;

    // Loop to count the number of cells
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (visited[i][j] == 0 && grid[i][j] == 1)
          count++;
      }
    }

    // Return the total count of cells
    return count;
  }

  public static void main(String[] args)
  {
    int N = 4;
    int[][] graph = { { 0, 0, 0, 0 },
                     { 1, 0, 1, 0 },
                     { 0, 1, 1, 0 },
                     { 0, 0, 0, 0 } };

    // Function call
    System.out.println(numberOfEnclaves(graph));
  }
}

// this code is contributed by ksam24000

Python3

# python3 code to implement the approach

# Function to run DFS on matrix
def dfs(grid, visited, row, col):

    if (row >= 0 and row < len(grid) and col >= 0
            and col < len(grid[0]) and grid[row][col] == 1
            and (not visited[row][col])):
        visited[row][col] = 1
        dfs(grid, visited, row + 1, col)
        dfs(grid, visited, row - 1, col)
        dfs(grid, visited, row, col + 1)
        dfs(grid, visited, row, col - 1)

# Function to find the number of cells
# from which we cannot walk out off boundary
def numberOfEnclaves(grid):

    n = len(grid)
    m = len(grid[0])
    visited = [[0 for _ in range(m)] for _ in range(n)]

    # If statement to reduce
    # the no of calls for the dfs
    for i in range(0, n):
        # First column
        if ((not visited[i][0]) and grid[i][0] == 1):
            dfs(grid, visited, i, 0)

        # Last column
        if ((not visited[i][m - 1]) and grid[i][m - 1] == 1):
            dfs(grid, visited, i, m - 1)

    for j in range(0, m):
        # First row
        if ((not visited[0][j]) and grid[0][j] == 1):
            dfs(grid, visited, 0, j)

        # Last row
        if ((not visited[n - 1][j]) and grid[n - 1][j] == 1):
            dfs(grid, visited, n - 1, j)

    count = 0

    # Loop to count the number of cells
    for i in range(0, n):
        for j in range(0, m):
            if ((not visited[i][j]) and grid[i][j] == 1):
                count += 1

    # Return the total count of cells
    return count

# Driver code
if __name__ == "__main__":

    N = 4
    graph = [[0 for _ in range(N)] for _ in range(N)]
    graph = [[0, 0, 0, 0],
             [1, 0, 1, 0],
             [0, 1, 1, 0],
             [0, 0, 0, 0]]

    # Function call
    print(numberOfEnclaves(graph))

    # This code is contributed by rakeshsahni

C#

// C# implementation
using System;
public class GFG {

  // Function to run DFS on matrix
  static void dfs(int[, ] grid, int[, ] visited, int row,
                  int col)
  {
    if (row >= 0 && row < grid.GetLength(0) && col >= 0
        && col < grid.GetLength(1)
        && grid[row, col] == 1
        && visited[row, col] == 0) {
      visited[row, col] = 1;
      dfs(grid, visited, row + 1, col);
      dfs(grid, visited, row - 1, col);
      dfs(grid, visited, row, col + 1);
      dfs(grid, visited, row, col - 1);
    }
  }

  // Function to find the number of cells
  // from which we cannot walk out off boundary
  public static int numberOfEnclaves(int[, ] grid)
  {
    int n = grid.GetLength(0);
    int m = grid.GetLength(1);
    int[, ] visited = new int[n, m];

    // If statement to reduce
    // the no of calls for the dfs
    for (int i = 0; i < n; i++) {
      // First column
      if (visited[i, 0] == 0 && grid[i, 0] == 1) {
        dfs(grid, visited, i, 0);
      }
      // Last column
      if (visited[i, m - 1] == 0
          && grid[i, m - 1] == 1) {
        dfs(grid, visited, i, m - 1);
      }
    }

    for (int j = 0; j < m; j++) {
      // First row
      if (visited[0, j] == 0 && grid[0, j] == 1) {
        dfs(grid, visited, 0, j);
      }
      // Last row
      if (visited[n - 1, j] == 0
          && grid[n - 1, j] == 1) {
        dfs(grid, visited, n - 1, j);
      }
    }

    int count = 0;

    // Loop to count the number of cells
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (visited[i, j] == 0 && grid[i, j] == 1)
          count++;
      }
    }

    // Return the total count of cells
    return count;
  }

  static public void Main()
  {
    int N = 4;
    int[, ] graph = new int[4, 4] { { 0, 0, 0, 0 },
                                   { 1, 0, 1, 0 },
                                   { 0, 1, 1, 0 },
                                   { 0, 0, 0, 0 } };

    // Function call
    Console.WriteLine(numberOfEnclaves(graph));
  }
}

// This code is contributed by ksam24000

Javascript

// JS code to implement the approach
// make 2d array
function makeArray(d1, d2) {
    var arr = new Array(d1), i, l;
    for(i = 0, l = d2; i < l; i++) {
        arr[i] = new Array(d1);
    }
    return arr;
}

// Function to run DFS on matrix
function dfs(grid ,visited ,row ,col)
{
    if (row >= 0 && row < grid.length && col >= 0
        && col < grid[0].length && grid[row][col] == 1
        && !visited[row][col]) {
        visited[row][col] = 1;
        dfs(grid, visited, row + 1, col);
        dfs(grid, visited, row - 1, col);
        dfs(grid, visited, row, col + 1);
        dfs(grid, visited, row, col - 1);
    }
}

// Function to find the number of cells
// from which we cannot walk out off boundary
function numberOfEnclaves(grid)
{
    let n = grid.length;
    let m = grid[0].length;
    let visited=makeArray(n,m);
    
    // If statement to reduce
    // the no of calls for the dfs
    for (let i = 0; i < n; i++) {
        // First column
        if (!visited[i][0] && grid[i][0] == 1) {
            dfs(grid, visited, i, 0);
        }
        // Last column
        if (!visited[i][m - 1] && grid[i][m - 1] == 1) {
            dfs(grid, visited, i, m - 1);
        }
    }

    for (let j = 0; j < m; j++) {
        // First row
        if (!visited[0][j] && grid[0][j] == 1) {
            dfs(grid, visited, 0, j);
        }
        // Last row
        if (!visited[n - 1][j] && grid[n - 1][j] == 1) {
            dfs(grid, visited, n - 1, j);
        }
    }

    let count = 0;

    // Loop to count the number of cells
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            if (!visited[i][j] && grid[i][j] == 1)
                count++;
        }
    }

    // Return the total count of cells
    return count;
}

// Driver code
    let N = 4;
    
    // call function to make 2d array
    let graph = makeArray(N,N);
    graph = [ [ 0, 0, 0, 0 ],
              [ 1, 0, 1, 0 ],
              [ 0, 1, 1, 0 ],
              [ 0, 0, 0, 0 ] ];

    // Function call
    console.log(numberOfEnclaves(graph));
 
 // This code is contributed by ksam24000.
Output

3

Time Complexity: O(N * N), As here we are using DFS on the matrix cells and traversing the whole matrix.
Auxiliary Space: O(N * N) The visited array of the same dimension as that of the given matrix


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!