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 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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide TagsDepth-first Search Breadth-first search Union FindHide Similar Problems(m) surrounded regions (m) Walls and Gates (H) Number of Islands II (m) number of Connected in a undirecte D Graph
Public classSolution {intR =-1; intC =-1; Public intNumislands (Char[] grid) {R=grid.length; if(R = = 0) return0; C= Grid[0].length; intCount = 0; for(intR = 0; r<r; ++r) { for(intc = 0; c<c; ++c) {if(Grid[r][c] = = ' 1 ') { ++count; } changeislandstowater (grid, R, c); } } returncount; } Private voidChangeislandstowater (Char[] Grid,intRintc) {if(R>=r | | c >=c | | r<0 | | c<0) return; if(Grid[r][c] = = ' 0 ') return; GRID[R][C]= ' 0 '; Changeislandstowater (grid, R, C+1);//Go RightChangeislandstowater (grid, r+1, C);//Go downChangeislandstowater (grid, R, C-1);//Go LeftChangeislandstowater (grid, r-1, C);//Go up }}
. Number of Islands