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


  • 相关阅读:
    Elasticsearch简介及C#操作库
    开发商城
    小程序源码下载[demo整理自github]
    基于vue的可视化编辑器
    Ocelot中文文档-Qos服务质量(转)
    干货 | Elasticsearch、Kibana数据导出实战
    java常用的框架介绍
    操作系统基础知识2
    操作系统基础知识
    计算机网络基础知识2
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13569930.html
Copyright © 2011-2022 走看看