Leetcode of depth-first search (DFS) Thematic -1020 The number of enclaves (Number of Enclaves)

Leetcode of depth-first search (DFS) Thematic -1020 The number of enclaves (Number of Enclaves)

Problem-solving depth-first search details, click


Given a two-dimensional array  A, each cell is 0 (representing the sea) or 1 (on behalf of the land).

Moving means go to the other place (one toward four directions) from a place on land or away from the boundary of the grid.

Returns the number of cells can not leave the land grid boundary moving any number of times in the grid.

 

Example 1:

Input: [[0,0,0,0], [1,0,1,0], [0,1,1,0], [0,0,0,0]] 
Output: 3 
Explanation: 
three 1 is surrounded by 0. A 1 is not surrounded, as it on the boundary.

Example 2:

Input: [[0,1,1,0], [0,0,1,0], [0,0,1,0], [0,0,0,0]] 
Output: 0 
Explanation: 
All 1 or both can reach the border at the border.

 

prompt:

  1. 1 <= A.length <= 500
  2. 1 <= A[i].length <= 500
  3. 0 <= A[i][j] <= 1
  4. All the lines are the same size

Ideas and 130 issues the same.

Proceed as follows:

  1. 1 find on the border, because only these 1, 1 and 1 connected with the border before they can reach the land.
  2. To find these 1 becomes 0
  3. Re-iterate, count the number 1 and returns.

  

AC Code:

class Solution {
    int dirx[] = {0,0,1,-1};
    int diry[] = {1,-1,0,0};
    public int numEnclaves(int[][] A) {
        if(A.length == 0 || A == null) return 0;
        int ans = 0;
        int vis[][] = new int[A.length][A[0].length];
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[0].length;j++){
                boolean flag = i==0||i==A.length-1||j==0||j==A[0].length-1;
                if(flag && A[i][j]==1){
                    change(A,i,j);
                }
            }
        }
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[0].length;j++){
                if(A[i][j]==1)
                    ans++;
            }
        }
        return ans;
    }
    
    public void change(int[][] A, int x, int y) {
        A[x][y] = 0;
        for (int i = 0; i < 4; i++) {
            int xx = x + dirx[i];
            int yy = y + diry[i];
            if (xx >= 0 && xx < A.length && yy >= 0 && yy < A[0].length
                    && A[xx][yy] == 1) {
                change(A, xx, yy);
            }
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11361470.html