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


  • 相关阅读:
    Java虚拟机JVM学习01 流程概述
    Java虚拟机JVM学习02 类的加载概述
    Java虚拟机JVM学习03 连接过程:验证、准备、解析
    Java虚拟机JVM学习04 类的初始化
    代码块(1)
    AtomicInteger
    简单的爬信息
    String.valueOf(null) 报空指针
    图片预览上传
    护城河
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13569930.html
Copyright © 2011-2022 走看看