求矩阵中连续1的个数 Number of Islands

为什么80%的码农都做不了架构师?>>>   hot3.png

问题:

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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

解决:

① 求岛屿数量的题的本质是求矩阵中连续区域的个数,采用DFS,基本思想是合并相邻的lands,合并通过递归完成。时间复杂度为O(m*n)。

class Solution { //6ms
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
        int m = grid.length;
        int n = grid[0].length;
        int count = 0;
        for (int i = 0;i < m;i ++){
            for (int j = 0;j < n;j ++){
                if (grid[i][j] == '1'){
                    count ++;
                    merge(grid,i,j);
                }
            }
        }
        return count;
    }
    public void merge(char[][] grid,int i,int j){
        int m = grid.length;
        int n = grid[0].length;
        if(i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != '1') return;
        grid[i][j] = '*';
        merge(grid,i - 1,j);
        merge(grid,i + 1,j);
        merge(grid,i,j - 1);
        merge(grid,i,j + 1);
    }
}

转载于:https://my.oschina.net/liyurong/blog/1572858

你可能感兴趣的:(求矩阵中连续1的个数 Number of Islands)