返回介绍

solution / 1900-1999 / 1905.Count Sub Islands / README_EN

发布于 2024-06-17 01:03:12 字数 8063 浏览 0 评论 0 收藏 0

1905. Count Sub Islands

中文文档

Description

You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

Return the _number of islands in _grid2 _that are considered sub-islands_.

 

Example 1:

Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.

Example 2:

Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2 
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.

 

Constraints:

  • m == grid1.length == grid2.length
  • n == grid1[i].length == grid2[i].length
  • 1 <= m, n <= 500
  • grid1[i][j] and grid2[i][j] are either 0 or 1.

Solutions

Solution 1: DFS

We can traverse each cell $(i, j)$ in the matrix grid2. If the value of the cell is $1$, we start a depth-first search from this cell, set the value of all cells connected to this cell to $0$, and record whether the corresponding cell in grid1 is also $1$ for all cells connected to this cell. If it is $1$, it means that this cell is also an island in grid1, otherwise it is not. Finally, we count the number of sub-islands in grid2.

The time complexity is $O(m \times n)$, and the space complexity is $O(m \times n)$. Here, $m$ and $n$ are the number of rows and columns of the matrices grid1 and grid2, respectively.

class Solution:
  def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
    def dfs(i: int, j: int) -> int:
      ok = grid1[i][j]
      grid2[i][j] = 0
      for a, b in pairwise(dirs):
        x, y = i + a, j + b
        if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y):
          ok = 0
      return ok

    m, n = len(grid1), len(grid1[0])
    dirs = (-1, 0, 1, 0, -1)
    return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])
class Solution {
  private final int[] dirs = {-1, 0, 1, 0, -1};
  private int[][] grid1;
  private int[][] grid2;
  private int m;
  private int n;

  public int countSubIslands(int[][] grid1, int[][] grid2) {
    m = grid1.length;
    n = grid1[0].length;
    this.grid1 = grid1;
    this.grid2 = grid2;
    int ans = 0;
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        if (grid2[i][j] == 1) {
          ans += dfs(i, j);
        }
      }
    }
    return ans;
  }

  private int dfs(int i, int j) {
    int ok = grid1[i][j];
    grid2[i][j] = 0;
    for (int k = 0; k < 4; ++k) {
      int x = i + dirs[k], y = j + dirs[k + 1];
      if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) {
        ok &= dfs(x, y);
      }
    }
    return ok;
  }
}
class Solution {
public:
  int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
    int m = grid1.size(), n = grid1[0].size();
    int ans = 0;
    int dirs[5] = {-1, 0, 1, 0, -1};
    function<int(int, int)> dfs = [&](int i, int j) {
      int ok = grid1[i][j];
      grid2[i][j] = 0;
      for (int k = 0; k < 4; ++k) {
        int x = i + dirs[k], y = j + dirs[k + 1];
        if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
          ok &= dfs(x, y);
        }
      }
      return ok;
    };
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        if (grid2[i][j]) {
          ans += dfs(i, j);
        }
      }
    }
    return ans;
  }
};
func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) {
  m, n := len(grid1), len(grid1[0])
  dirs := [5]int{-1, 0, 1, 0, -1}
  var dfs func(i, j int) int
  dfs = func(i, j int) int {
    ok := grid1[i][j]
    grid2[i][j] = 0
    for k := 0; k < 4; k++ {
      x, y := i+dirs[k], j+dirs[k+1]
      if x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && dfs(x, y) == 0 {
        ok = 0
      }
    }
    return ok
  }
  for i := 0; i < m; i++ {
    for j := 0; j < n; j++ {
      if grid2[i][j] == 1 {
        ans += dfs(i, j)
      }
    }
  }
  return
}
function countSubIslands(grid1: number[][], grid2: number[][]): number {
  const [m, n] = [grid1.length, grid1[0].length];
  let ans = 0;
  const dirs: number[] = [-1, 0, 1, 0, -1];
  const dfs = (i: number, j: number): number => {
    let ok = grid1[i][j];
    grid2[i][j] = 0;
    for (let k = 0; k < 4; ++k) {
      const [x, y] = [i + dirs[k], j + dirs[k + 1]];
      if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
        ok &= dfs(x, y);
      }
    }
    return ok;
  };
  for (let i = 0; i < m; ++i) {
    for (let j = 0; j < n; j++) {
      if (grid2[i][j]) {
        ans += dfs(i, j);
      }
    }
  }
  return ans;
}

Solution 2

class Solution:
  def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
    def bfs(i: int, j: int) -> int:
      ok = grid1[i][j]
      q = deque([(i, j)])
      grid2[i][j] = 0
      while q:
        i, j = q.popleft()
        for a, b in pairwise(dirs):
          x, y = i + a, j + b
          if 0 <= x < m and 0 <= y < n and grid2[x][y]:
            q.append((x, y))
            ok = ok & grid1[x][y]
            grid2[x][y] = 0
      return ok

    m, n = len(grid1), len(grid1[0])
    dirs = (-1, 0, 1, 0, -1)
    return sum(bfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文