DFS--小岛问题(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

解法1:

public int numIslands(char[][] grid) {
        // 参数校验
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }

        // 元素默认值是false
        boolean[][] visited = new boolean[grid.length][grid[0].length];

        int result = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                // 如果此位置没有被访问过,并且此位置是岛,就里德广度优先遍历
                if (!visited[i][j] && grid[i][j] == '1') {
                    result++;
                    bfs(grid, visited, i, j);
                }
            }
        }
        return result;
    }

    private void bfs(char[][] grid, boolean[][] visited, int row, int col) {

        if (row >= 0 && row < grid.length // 行合法
                && col >= 0 && col < grid[0].length // 列合法
                && !visited[row][col] // 没有访问过
                && grid[row][col] == '1') { // 是岛上陆地

            // 标记此位置已经访问过了
            visited[row][col] = true;

            // 上
            bfs(grid, visited, row - 1, col);
            // 右
            bfs(grid, visited, row, col + 1);
            // 下
            bfs(grid, visited, row + 1, col);
            // 左
            bfs(grid, visited, row, col - 1);

        }
    }

解法2:


        static void helperNumIsland(char[][]grid, int x, int y){

        if (x<0 || y<0 ||x== grid.length|| y == grid[0].length ||grid[x][y]=='0'){
            return;
        }

        if(grid[x][y]=='1'){
            grid[x][y] = 'x';
        }else{
            return;
        }

        helperNumIsland(grid,x+1,y);
        helperNumIsland(grid,x-1,y);
        helperNumIsland(grid,x,y+1);
        helperNumIsland(grid,x,y-1);
    }
    
    public int numIslands(char[][] grid) {
                int count =0;

        for(int x=0;x

你可能感兴趣的:(DFS--小岛问题(Number of Islands))