zoukankan      html  css  js  c++  java
  • 200. Number of Islands 200.岛屿数(可以形状一样)

    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: grid = [
      ["1","1","1","1","0"],
      ["1","1","0","1","0"],
      ["1","1","0","0","0"],
      ["0","0","0","0","0"]
    ]
    Output: 1
    

    Example 2:

    Input: grid = [
      ["1","1","0","0","0"],
      ["1","1","0","0","0"],
      ["0","0","1","0","0"],
      ["0","0","0","1","1"]
    ]
    Output: 3

    思路:不知道递归过程中怎么数数,应该在主函数里面写啊。

    class Solution {
        public int numIslands(char[][] grid) {
            //cc
            if (grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int count = 0;
            
            //每一个点逐一比较
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    if (grid[i][j] == '1') {
                        dfs(grid, i, j);
                        count++;
                    }
                }
            }
            
            return count;
        }
        
        //返回面积
        public int dfs(char[][] grid, int x, int y) {
            //标记
            if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 
               grid[x][y] == '1') {             
                    grid[x][y] = '0';
                                  
                    dfs(grid, x - 1, y); 
                    dfs(grid, x + 1, y);
                    dfs(grid, x, y - 1);
                    dfs(grid, x, y + 1);         
            }
            
            return 0;
        }
    }
    View Code


  • 相关阅读:
    【模板】高斯消元
    【洛谷P1730】最小密度路径
    【模板】矩阵乘法优化线性递推
    【洛谷P3723】礼物
    【洛谷P3338】力
    【模板】NTT
    【洛谷P1919】A*B Problem升级版
    测试理论基础(思维导图)
    Fiddler
    常用 Linux 命令
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13569930.html
Copyright © 2011-2022 走看看