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
This problem does not start at first, refer to the practice of the great God, with the DFS practice, build a visited two-dimensional array record ' 1 ' has been visited. Add 1 to the result only if you have not visited ' 1 '.
Public intNumislands (Char[,] grid) { introw = grid. GetLength (0); intCol = grid. GetLength (1); varvisited =New BOOL[Row,col]; intres =0; for(inti =0;i< row;i++) { for(intj =0;j< col;j++) { if(Grid[i,j] = ='1'&&!Visited[i,j]) {dfsmarkvisted (grid,i,j,visited); Res++; } } } returnRes; } Private voidDfsmarkvisted (Char[,] grid,intXintYBOOL[,] visited) { if(X <0|| x>= grid. GetLength (0))return; if(Y <0|| y>= grid. GetLength (1))return; if(Grid[x,y]! ='1'|| Visited[x,y])return; Visited[x,y]=true; dfsmarkvisted (Grid,x-1, y,visited); dfsmarkvisted (Grid,x+1, y,visited); dfsmarkvisted (Grid,x,y-1, visited); dfsmarkvisted (Grid,x,y+1, visited); }
similar topics are:
(M) surrounded regions(M) Walls and Gates(H) Number of Islands II(M) number of Connected components in an undirected Graph
. Number of Islands