首页 > 编程语言 > 详细

200. Number of Islands java solutions

时间:2016-07-04 11:27:42      阅读:144      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/guoguolan/p/5639706.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!