200. Number of Islands java solutions
Posted Miller1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了200. Number of Islands java solutions相关的知识,希望对你有一定的参考价值。
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 is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are 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 class Solution { 2 public int numIslands(char[][] grid) { 3 if(grid == null || grid.length == 0 || grid[0].length == 0) return 0; 4 int m = grid.length, n = grid[0].length; 5 boolean[][] visit = new boolean[m][n]; 6 int ans = 0; 7 for(int i = 0; i < m;i++){ 8 for(int j = 0; j < n; j++){ 9 if(visit[i][j] != true && grid[i][j] == ‘1‘){ 10 ans++; 11 BFS(visit,grid,i,j); 12 } 13 } 14 } 15 return ans; 16 } 17 18 public void BFS(boolean[][] visit, char[][] grid, int row, int col){ 19 if(row >=0 && row < visit.length && col >=0 && col < visit[0].length 20 && visit[row][col] != true && grid[row][col] == ‘1‘){ 21 visit[row][col] = true; 22 BFS(visit,grid,row-1,col);//上下左右 23 BFS(visit,grid,row+1,col); 24 BFS(visit,grid,row,col-1); 25 BFS(visit,grid,row,col+1); 26 } 27 } 28 }
以上是关于200. Number of Islands java solutions的主要内容,如果未能解决你的问题,请参考以下文章