Number of Islands

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.

思路:

  bfs+dfs的结合体

我的代码:

public class Solution {

    public int numIslands(char[][] grid) {

        if(grid==null || grid.length==0 || grid[0].length==0 )    return 0;

        int row = grid.length;

        int col = grid[0].length;

        boolean[][] isVisited = new boolean[row][col];

        int rst = 0;

        for(int i = 0; i < row; i++)

        {

            for(int j = 0; j < col; j++)

            {

                if(!isVisited[i][j] && grid[i][j]=='1')

                {

                    rst++;

                    helper(grid,isVisited, i, j);

                }

            }

        }

        return rst;

    }

    public void helper(char[][] grid,boolean[][] isVisited, int i, int j)

    {

        int row = grid.length;

        int col = grid[0].length;

        isVisited[i][j] = true;

        //top

        if(i != 0 && grid[i-1][j] == '1' && !isVisited[i-1][j])    helper(grid, isVisited, i-1, j);

        //down

        if(i != row-1 && grid[i+1][j] == '1' && !isVisited[i+1][j])    helper(grid, isVisited, i+1, j);

        //left

        if(j != 0 && grid[i][j-1] == '1' && !isVisited[i][j-1])    helper(grid, isVisited, i, j-1);

        //right

        if(j != col-1 && grid[i][j+1] == '1' && !isVisited[i][j+1])    helper(grid, isVisited, i, j+1);

    }

}
View Code

他人代码:

public class Solution {

    static int[] dx = {1, 0, 0, -1};

    static int[] dy = {0, 1, -1, 0};

    private int n, m;

    

    private void removeIsland(char[][] grid, int x, int y) {

        grid[x][y] = '0';

        for (int i = 0; i < 4; i++) {

            int nextX = x + dx[i];

            int nextY = y + dy[i];

            if (nextX >= 0 && nextX < n && nextY >= 0 && nextY < m) {

                if (grid[nextX][nextY] == '1') {

                    removeIsland(grid, nextX, nextY);

                }

            }

        }

    }

    

    public int numIslands(char[][] grid) {

        n = grid.length;

        if (n == 0) {

            return 0;

        }

        

        m = grid[0].length;

        if (m == 0) {

            return 0;

        }

        

        int count = 0;

        for (int i = 0; i < n; i++) {

            for (int j = 0; j < m; j++) {

                if (grid[i][j] == '1') {

                    removeIsland(grid, i, j);

                    count++;

                }

            }

        }

        

        return count;

    }

}
View Code

学习之处:

  • dfs是指一步步的深入的去访问每一个节点 bfs是指上下左右四个方向去访问
  • 别人的代码有两个好处,第一个好处通过声明数组,便代表了四个方向,就可以用循环去做了而不用还得手写方向,加1减1啊,另外一个好的地方,别人代码中没用用到isVisited数组,而是他判断是否isVisited把之前的数组的元素变成0,便起到了判断isVisited的功能,节约了空间。

你可能感兴趣的:(number)