Given a 2d grid map ‘1‘
of S (land) ‘0‘
and S (water), count the number of islands. An island is surrounded by water and are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer:1
Example 2:
11000
11000
00100
00011
Answer:3
1 Public classSolution {2 Public intNumislands (Char[,] grid) {3 if(grid==NULL|| Grid. GetLength (0)==0|| Grid. GetLength (1)==0)4 {5 return 0;6 }7 inth = grid. GetLength (0);8 intW = grid. GetLength (1);9 intCount =0;Ten //Create 2D bool Array to record the islands has been visited One BOOL[,] visit =New BOOL[h,w]; A //Find the first ' 1 ' on island and find all other ' 1 ' s by calling Bfs; - for(intI=0; i) - { the for(intj=0; j<w; J + +) - { - //Only check unvisited ones - if(!visit[i,j] && grid[i,j]=='1') + { -count++; + Bfs (grid, visit, I, j); A } at } - } - returncount; - } - //Breadth-first Search to find all ' 1 ' in this island and the flip visit to true; - Private voidBfs (Char[,] grid,BOOL[,] visit,intRowintCol) in { - inth = grid. GetLength (0); to intW = grid. GetLength (1); + if(row>=0&& row0&& col<w &&!visit[row,col] && grid[row,col]=='1') - { the //Flip Visit *visit[row,col]=true; $ //element abovePanax NotoginsengBfs (grid, visit, row-1, col); - //element below theBfs (grid, visit, row+1, col); + //element Left ABfs (grid, visit, Row, col-1); the //element Right +Bfs (grid, visit, Row, col+1); - } $ } $}
Leetcode 200. Number of Islands