leetcode 200. Number of Islands

Posted jamieliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 200. Number of Islands相关的知识,希望对你有一定的参考价值。

Given a 2d grid map of ‘1‘s (land) and ‘0‘s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

 

第一次用DFS,基本思路就是遍历表中的每一个元素,将‘1’标记为‘0’,同时访问它上下左右的元素并且逐个标记为零,每访问一个元素,首先访问该元素的相邻,不停地deep search下去,然后再一级一级向上返回,返回上一个元素的不同方向的元素。

class Solution {
    int m; //这里一定要用全局变量,不然DFSMarking里面的m和n不起作用
    int n;
    public int numIslands(char[][] grid) {
        n = grid.length;
        if(n == 0) return 0;
        m = grid[0].length;
        int count = 0;
        for(int i=0; i<n; i++) {
            for(int j=0; j<m; j++) {
                if(grid[i][j] == 1){
                    DFSMarking(grid, i, j);
                    count++;
                }
            }
        }
        return count;
    }
    
    public void DFSMarking(char[][] grid, int i, int j) {
        if(i<0 || j<0 || i>n-1 || j>m-1 || grid[i][j] != 1) return;
        grid[i][j] = 0;
        DFSMarking(grid,i+1,j);
        DFSMarking(grid,i-1,j);
        DFSMarking(grid,i,j+1);
        DFSMarking(grid,i,j-1);
    }
}

 

以上是关于leetcode 200. Number of Islands的主要内容,如果未能解决你的问题,请参考以下文章

leetcode200 Number of Islands

Leetcode 200. Number of Islands

[leetcode-200-Number of Islands]

leetcode 200. Number of Islands

leetcode--200. Number of Islands

[LeetCode] 200. Number of Islands(岛屿的数目)