[Leedcode 200] 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:

11110
11010
11000
00000

Answer:1

Example 2:

11000
11000
00100
00011

Answer:3

 Public classSolution { Public intNumislands (Char[] grid) {        //Dfs thought that when a node is found to be 1 o'clock, all nodes adjacent to it need to be set to 0, and this method will change the value of the original grid.        if(grid==NULL|| grid.length<=0)return0; introw=grid.length; intCol=grid[0].length; intCount=0;  for(inti=0;i<row;i++){             for(intj=0;j<col;j++){                if(grid[i][j]== ' 1 ') {Count++;                DFS (GRID,I,J); }            }        }        returncount; }     Public voidDfsChar[] Grid,intIintj) {        if(i<0| | i>grid.length-1| | j<0| | J&GT;GRID[0].LENGTH-1)return; if(grid[i][j]== ' 1 ') {Grid[i][j]= ' 0 '; DFS (Grid,i-1, J); DFS (Grid,i+1, J); DFS (Grid,i,j-1); DFS (Grid,i,j+1); }    }}

[Leedcode 200] Number of Islands

Contact Us

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.