Number LeetCode 200. islands

1. Topic

https://leetcode-cn.com/problems/number-of-islands/

2. problem solution

This question My first reaction solution is out of the DFS ;
the DFS, Depth First Search. The depth of the first search, which was originally from the tree structure of the algorithm is to have all of the nodes under a node search play, fishes next node to search. Meaning that this title on every search should look around to diverge, surrounded by no one knows, can no longer continue the search down so far.
This question object idea is applied to the following cases:
Case 1: the first one, plus one island;
Case 2: surrounded by 0, 1 plus the number of islands;
we partially coupled as a horizontal and vertical overall, then this thing is simple. When we encounter 1, plus one of our islands, and the use of BFS on the surrounding continue to judge, one of us (adjacent 1) directly to pull him to come and he is set to 0, to avoid interference; it is not direct return; until then encountered the next 1, back and forth through the bad, you can get all the islands;

3. Code

class Solution {
    public int numIslands(char[][] grid) {
        if(grid==null|| grid.length == 0 || grid[0].length == 0){
            return 0;
        }
        int rows=grid.length;//行
        int cols=grid[0].length;//列
        int result=0;
        for(int i=0;i<rows;i++){
            for (int j=0; j<cols; j++) {
                if(grid[i][j]=='1'){
                    result++;
                    bfsInstand(i,j,rows,cols,grid);
                }
            }
        }
        return result;
    }
     private static void bfsInstand(int i,int j,int rows,int cols,char[][] grid){
        if(i<0||i>=rows||j<0||j>=cols){
            return;
        }
        if(grid[i][j]=='0'){
            return;
        }
        grid[i][j]='0';

        bfsInstand(i+1,j,rows,cols,grid);
        bfsInstand(i,j+1,rows,cols,grid);
        bfsInstand(i-1,j,rows,cols,grid);
        bfsInstand(i,j-1,rows,cols,grid);

    }
}

4. Results screenshot

3103903-631fd7af3b8c7dd6.png
image.png

Reproduced in: https: //www.jianshu.com/p/b0e2e88560e6

Guess you like

Origin blog.csdn.net/weixin_33711641/article/details/91113951