# . Number of Islands

Source: Internet
Author: User

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:

`11110110101100000000`

Example 2:

`11000110000010000011`

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

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.