LeetCode - Number of Islands (DFS)

Topic description

image.png

Problem solving ideas

The number of islands is a classic DFS problem. To solve this problem, we must first understand the following problems:

RQ1: How to judge it is an island?

It is not that a place with 1 is an island. An isolated island has no 1 on the top, bottom, left and right sides. Only such an island can be counted as an island, which is why so many 1s in the first example are an island. The reason, see the following example, there are three islands in this picture:

image.png

RQ2: How does DFS solve the problem of the number of islands?

The second question is the core of our problem-solving. The core idea is just one sentence.假如当前遍历的元素的值是1,就将岛屿数量加1,同时将其上下左右的1都变为0,然后继续循环。

problem solving code

var numIslands = function (grid) {
    
    
    // 岛屿的数量是一道经典的DFS问题
    let row = grid.length;
    let column = grid[0].length;
    let count = 0;
    for (let i = 0; i < row; i++) {
    
    
        for (let j = 0; j < column; j++) {
    
    
            if (grid[i][j] === '1') {
    
    
                count++;
                dfs(i,j,grid);
            }
        }
    }
    return count;
    function dfs(i,j,grid) {
    
    
        if (i < 0 || i >= row || j < 0 || j >= column || grid[i][j] === '0') {
    
    
            return;
        }
        grid[i][j] = '0';
        dfs(i+1,j,grid);
        dfs(i,j+1,grid);
        dfs(i-1,j,grid);
        dfs(i,j-1,grid);
    }

};

Similar comparison

The number of islands and the maximum area of ​​islands can be described as twin problems, both of which can be solved by DFS, and the structure of the entire code is highly similar, the difference is that the number of islands enters the DFS function. , and the core of the maximum area of ​​the island is to add 1 to the top, bottom, left, and right and return to calculate the maximum value. Therefore, whether at work or when writing questions, we must summarize the same type of questions.

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/123198806