【dfs】B013_飞地的数量(dfs「碰边法 | Flood fill」)

一、题目描述

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, 
or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off 
the boundary of the grid in any number of moves.

Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: 
There are three 1s that are enclosed by 0s, 
and one 1 that isn't enclosed because its on the boundary.

二、题解

这题和统计封闭岛屿的数量很像,但是有我用「碰边法」做不对。 这里记录一下暂时错误的解法, *待更正

方法一:dfs(碰边法)

class Solution {
  int step = 0;
  int m, n;
  boolean meetEdge;

  public int numEnclaves(int[][] grid) {
    m = grid.length;
    n = grid[0].length;
    for (int x = 0; x < m; x++)
    for (int y = 0; y < n; y++) {
      if (grid[x][y] == 1) {
        meetEdge = false;
        dfs(grid, x, y);
        if (meetEdge == true)
          step = 0;
      }
    }
    return step;
  }
  private void dfs(int[][] grid, int x, int y) {
      if (x < 0 || x >= m || y < 0 || y >= n) {
        meetEdge = true;
        return;
      }
      if (grid[x][y] != 1)    
        return;
      step++;
      grid[x][y] = 0;
      
      dfs(grid, x-1, y);
      dfs(grid, x+1, y);
      dfs(grid, x, y-1);
      dfs(grid, x, y+1);
  }
}

复杂度分析

  • 时间复杂度: O ( n × m ) O(n × m)
  • 空间复杂度: O ( n × m ) O(n × m)

方法二:dfs(Flood fill)

算法
  • 从第一和最后一行的岛屿和与之相连的岛屿开始淹没。
  • 从第一和最后一列和岛屿和与之相连的岛屿开始淹没。
  • 最后数出 1 的个数即可。
int step = 0;
int m, n;

public int numEnclaves(int[][] grid) {
  m = grid.length;
  n = grid[0].length;
  //从第一和最后一行的岛屿开始淹没
  for (int y = 0; y < n; y++) {
    dfs(grid, 0, y);
    dfs(grid, m-1, y);
  }
  //从第一和最后一列的岛屿开始淹没
  for (int x = 0; x < m; x++) {
    dfs(grid, x, 0);
    dfs(grid, x, n-1);
  }
  //最后数数即可
  for (int x = 1; x < m; x++)
  for (int y = 1; y < n; y++) {
    if (grid[x][y] == 1) {
      step++;
    }
  }
  return step;
}
//深搜
private void dfs(int[][] grid, int x, int y) {
  if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != 1 ) {
    return;
  }
  grid[x][y] = 0;	//淹没岛屿
  dfs(grid, x-1, y);
  dfs(grid, x+1, y);
  dfs(grid, x, y-1);
  dfs(grid, x, y+1);
}

复杂度分析

  • 时间复杂度: O ( n × m ) O(n × m)
  • 空间复杂度: O ( n × m ) O(n × m)
发布了461 篇原创文章 · 获赞 102 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104761598