Leetcode 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 public class Solution {
 2     public int NumIslands(char[,] grid) {
 3         if(grid==null||grid.GetLength(0)==0||grid.GetLength(1)==0)
 4         {
 5             return 0;
 6         }
 7         int h = grid.GetLength(0);
 8         int w = grid.GetLength(1);
 9         int count = 0;
10         // Create 2D bool array to record the islands have been visited
11         bool[,] visit = new bool[h,w];
12         //find the first '1' on island and find all other '1's by calling Bfs;
13         for(int i=0; i<h; i++)
14         {
15             for(int j=0; j<w; j++)
16             {
17                 //only check unvisited ones
18                 if(!visit[i,j] && grid[i,j]=='1')
19                 {
20                     count++;
21                     Bfs(grid, visit , i , j);
22                 }
23             }
24         }
25         return count;
26     }
27     //Breadth-first Search to find all '1's on this island and flip visit to true;
28     private void Bfs(char[,] grid, bool[,] visit, int row, int col)
29     {
30         int h = grid.GetLength(0);
31         int w = grid.GetLength(1);
32         if(row>=0&& row<h && col>=0 && col<w && !visit[row,col] && grid[row,col]=='1')
33         {
34             //flip visit
35             visit[row,col]=true;
36             //element above 
37             Bfs(grid, visit, row-1, col);
38             //element below
39             Bfs(grid, visit, row+1, col);
40             //element left
41             Bfs(grid, visit, row, col-1);
42             //element right
43             Bfs(grid, visit, row, col+1);
44         }
45     }
46 }

 

转载于:https://www.cnblogs.com/MiaBlog/p/6041173.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值