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 }

 

posted @ 2016-11-07 23:47  MiaBlog  阅读(129)  评论(0编辑  收藏  举报