Number of Enclaves in C++



Suppose we have given a 2D array A, now each cell is 0 (representing sea) or 1 (representing land) Here a move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid. We have to find the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves. So if the grid is like −

0 0 0 0
1 0 1 0
0 1 1 0
0 0 0 0

The answer will be 3, as there are three ones enclosed by 0s, and one 1 is not enclosed.

To solve this, we will follow these steps −

  • Make a direction array dir, and store [[1,0], [-1,0], [0,1], [0,-1]]

  • make a method called dfs() this will take x, y and the matrix A

  • if x < 0 or y > 0 or x > row count of A or y > column counts of A, or A[x, y] is 0, then return

  • set A[x, y] := 0

  • for k in range 0 to 3

    • nx := dir[k, 0] + x, ny := dir[k, 1] + y

    • dfs(nx, ny, A)

  • From the main method do the following

  • ret := 0, n := row count of A

  • m := column count of A if n is not 0, otherwise m := 0

  • for i in range 0 to n – 1

    • if A[i, 0] = 1, then call dfs(i, 0, A)

    • if A[i, m – 1] is 1, then call dfs(i, m – 1, A)

  • for i in range 0 to m – 1

    • if A[0, i] = 1, then call dfs(0, i, A)

    • if A[n – 1, i] is 1, then call dfs(n – 1, i, A)

  • for i in range 0 to n – 1

    • for j in range 0 to m – 1

      • ret := ret + A[i, j]

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
class Solution {
   public:
   void dfs(int x, int y, vector < vector <int>>& A){
      if(x < 0 || y < 0 || x >= A.size() || y >= A[0].size() ||
      A[x][y] == 0) return;
      A[x][y] = 0;
      for(int k = 0; k < 4; k++){
         int nx = dir[k][0] + x;
         int ny = dir[k][1] + y;
         dfs(nx, ny, A);
      }
   }
   int numEnclaves(vector<vector<int>>& A) {
      int ret = 0;
      int n = A.size();
      int m = n ? A[0].size() : 0;
      for(int i = 0; i < n; i++){
         if(A[i][0] == 1){
            dfs(i, 0, A);
         }
         if(A[i][m - 1] == 1){
            dfs(i, m - 1, A);
         }
      }
      for(int i = 0; i < m; i++){
         if(A[0][i] == 1){
            dfs(0, i, A);
         }
         if(A[n - 1][i] == 1){
            dfs(n - 1, i, A);
         }
      }
      for(int i = 0; i < n; i++){
         for(int j = 0; j < m; j++){
            ret += A[i][j];
         }
      }
      return ret;
   }
};
main(){
   vector<vector<int>> v1 = {{0,0,0,0},{1,0,1,0},{0,1,1,0},{0,0,0,0}};
   Solution ob;
   cout << (ob.numEnclaves(v1));
}

Input

[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]

Output

3
Updated on: 2020-04-30T14:24:45+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements