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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

题目大意:给定一个2维数组,0代表水,1代表陆地,求岛屿的数量,相邻的陆地算一个岛屿。
比如:


Leetcode解题报告——200. Number of Islands_第1张图片
image.png

上图 岛屿数为 3

大概思路:用一个二维 bool 数组作为辅助数组,用来标记该节点是否访问过,然后循环遍历原数组中的每个节点,如果该节点的值为1,且没有被访问过,则岛屿数 +1,然后对该岛屿上下左右进行深度遍历,只标记而不增加岛屿数。

代码如下:

 public static int numIslands(char[][] grid) {
        if(grid.length < 1) return 0;
        int count = 0;
        boolean [][] searched = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == '0' || searched[i][j] == true) continue;
                count += 1;
                dfs(grid,searched,i,j);
            }
        }
        return count;
    }

    public  static void dfs(char[][]grid,boolean [][] used,int i,int j){
                if(grid[i][j] == '0' || used[i][j] == true) return;
                used[i][j] = true;
                if(i < grid.length-1) dfs(grid,used,i+1,j);
                if(i > 0) dfs(grid,used,i-1,j);
                if(j < grid[0].length -1) dfs(grid,used,i,j+1);
                if(j > 0) dfs(grid,used,i,j-1);
    }

你可能感兴趣的:(Leetcode解题报告——200. Number of Islands)