Number of Islands

https://leetcode.com/problems/number-of-islands/
给定一个二维数组,由0和1构成,1代表土地,0代表海水。连起来的1表明是一个小岛(水平或者垂直相连),求一共有多少个小岛
example:
Input:
11110
11010
11000
00000
Output: 1

思路1

很明显,拿到题,上手就是一个DFS大法,深度优先遍历,遍历的是什么东西? 遍历的是以(i,j)开始,值为1的相连土地的所有点, just like a kind of virus,疯狂蔓延
talk is cheap,show me your example

i=0,j=0  grid[0][0] = '1'  请开始你的蔓延,
因为这个蔓延会蔓延到与它相邻的所有1, 
 所以此处cnt++(表明岛屿的数量加一) ,
然后继续蔓延
------------------------------------------------------------------
   islandHelper(grid,visited,0,0)  由于grid[0][0] = ‘1’ ,置visited[0][0] = 1
   继续对(-1,0),(1,0),(0,-1),(0,1)四个方向的土壤继续islandHelper
------------------------------------------------------------------
          islandHelper(grid,visited,-1,0),  越界,return
------------------------------------------------------------------
          islandHelper(grid,visited,1,0),  grid[1][0] = '1',置放visited[1][0] = 1
          继续对(0,0),(2,0),(1,-1),(1,1) 四个方向的土壤继续islandHelper
------------------------------------------------------------------
          islandHelper(grid,visited,0,1),  grid[0][1] = '1',置放visited[0][1] = 1
          继续对(-1,1),(1,1),(0,0),(0,2) 四个方向的土壤继续islandHelper
 //DFS
    public int numIslands(char[][] grid) {
        if (grid.length == 0) {
            return 0;
        }
        int width = grid[0].length;
        int height = grid.length;
        int[][] visited = new int[height][width];
        int cnt = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (visited[i][j] == 1 || grid[i][j] == '0') {
                    continue;
                }
                cnt++;
                islandHelper(grid,visited,i,j);
            }
        }
        return cnt;
    }

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

你可能感兴趣的:(Number of Islands)