Skip to content

1020. Number of Enclaves 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  int numEnclaves(vector<vector<int>>& A) {
    const int m = A.size();
    const int n = A[0].size();

    // Remove lands connected to edge
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (i * j == 0 || i == m - 1 || j == n - 1)
          if (A[i][j] == 1)
            dfs(A, i, j);

    return accumulate(begin(A), end(A), 0, [](int s, vector<int>& row) {
      return s + accumulate(begin(row), end(row), 0);
    });
  }

 private:
  void dfs(vector<vector<int>>& A, int i, int j) {
    if (i < 0 || i == A.size() || j < 0 || j == A[0].size())
      return;
    if (A[i][j] == 0)
      return;

    A[i][j] = 0;
    dfs(A, i + 1, j);
    dfs(A, i - 1, j);
    dfs(A, i, j + 1);
    dfs(A, i, j - 1);
  };
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
  public int numEnclaves(int[][] A) {
    final int m = A.length;
    final int n = A[0].length;

    // Remove lands connected to edge
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        if (i * j == 0 || i == m - 1 || j == n - 1)
          if (A[i][j] == 1)
            dfs(A, i, j);

    int ans = 0;

    for (int[] row : A)
      ans += Arrays.stream(row).sum();

    return ans;
  }

  private void dfs(int[][] A, int i, int j) {
    if (i < 0 || i == A.length || j < 0 || j == A[0].length)
      return;
    if (A[i][j] == 0)
      return;

    A[i][j] = 0;
    dfs(A, i + 1, j);
    dfs(A, i - 1, j);
    dfs(A, i, j + 1);
    dfs(A, i, j - 1);
  }
}