Number of Islands Java solutions

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

1  Public classSolution {2      Public intNumislands (Char[] grid) {3         if(Grid = =NULL|| Grid.length = = 0 | | Grid[0].length = = 0)return0;4         intm = grid.length, n = grid[0].length; 5         Boolean[] Visit =New Boolean[m][n];6         intAns = 0;7          for(inti = 0; I < m;i++){8              for(intj = 0; J < N; J + +){9                 if(Visit[i][j]! =true&& Grid[i][j] = = ' 1 '){Tenans++; One BFS (visit,grid,i,j); A                 } -             } -         } the         returnans; -     } -      -      Public voidBFS (Boolean[] Visit,Char[] Grid,intRowintCol) { +         if(Row >=0 && row < visit.length && Col >=0 && Col < visit[0].length -&& Visit[row][col]! =true&& Grid[row][col] = = ' 1 '){ +Visit[row][col] =true; ABFS (Visit,grid,row-1,col);//Up or down atBFS (visit,grid,row+1, col); -BFS (visit,grid,row,col-1); -BFS (visit,grid,row,col+1); -         } -     } -}

Number of Islands Java solutions

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.