[Dfs] number B013_ enclaves (dfs "butt edge method | Flood fill")

One, Title Description

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.

Second, the problem solution

This question and count the number of closed islands like, but I have "touched edge law" do not. Here the record about being the wrong solution, * to be correct

Method a: dfs (butt edge method)

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);
  }
}

Complexity Analysis

  • time complexity: O ( n × m ) O(n × m)
  • Space complexity: O ( n × m ) O(n × m)

Method two: dfs (Flood fill)

algorithm
  • The island is connected to the first and last line of islands and submerged begin with.
  • Start from the first and the last submerged an island and island and connected thereto.
  • Finally, to count the number of 1's.
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);
}

Complexity Analysis

  • time complexity: O ( n × m ) O(n × m)
  • Space complexity: O ( n × m ) O(n × m)
Published 461 original articles · won praise 102 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/104761598
dfs