200. 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:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

题目含义:所有1连起来可以构成一个岛,求岛的个数

复制代码
 1     private void IslandCount(char[][] grid,int i,int j){
 2         if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == '0') return;
 3         grid[i][j] = '0';
 4         IslandCount(grid, i - 1, j);
 5         IslandCount(grid, i + 1, j);
 6         IslandCount(grid, i, j - 1);
 7         IslandCount(grid, i, j + 1);
 8     }
 9     
10     public int numIslands(char[][] grid) {
11         if (grid.length == 0) return 0;
12         int count = 0;
13         for (int i = 0; i < grid.length; i++) {
14             for (int j = 0; j < grid[0].length; j++) {
15                 if (grid[i][j] == '1') {
16                     IslandCount(grid, i, j);
17                     count++;
18                 }
19             }
20         }
21         return count;         
22     }
复制代码

 

posted @   daniel456  阅读(134)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示