# LeetCode 200. Number of Islands

91人阅读 评论(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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3

/**
* Created by kyle on 2016/6/1.
*/
public class NumberOfIsland  {

static  void dfs(char[][] map, int i ,int j){
int m = map.length;
int n = map[0].length;
if(map[i][j] == '0'){
return;
}

if(map[i][j] =='2'){
return;
}

if(map[i][j] == '1'){
map[i][j] = '2';
}

if(i+1 < m){
dfs(map, i+1, j);
}
if(j+1 < n){
dfs(map, i, j+1);
}

if(i-1 >=0){
dfs(map, i-1, j);

}

if( j- 1 >= 0){
dfs(map ,i, j-1);
}

}

static  int numberOfIsland(char[][] grid){

if(grid == null){
return  0;
}
if(grid.length == 0 || grid[0].length == 0){
return  0;
}
int m = grid.length;
int n = grid[0].length;
int count = 0;

for( int i =0 ; i< m ; i++){
for(int j = 0 ; j< n ; j++){
if(grid[i][j] == '1'){
dfs(grid , i ,j );
//  show(grid);

count++;
}
}
}
return  count;
}
static  void show(char[][] islandMap){
System.out.println("island map :");
for(int i =0 ;i< islandMap.length ; i++){
System.out.println(Arrays.toString(islandMap[i]));
}
}

static  public  void main(String[] args){
/*char[][] islandMap = {
{'1','1','1','0','0'},
{'1','1','0','1','0'},
{'0','0','1','0','0'},
{'0','0','0','1','1'},
};*/

char[][] islandMap = {
{'1','1','1'},
{'0','1','0'},
{'1','1','1'}
};

// dfs(islandMap, 0, 0);
// int number = numberOfIsland(new int[0][0]);
int number = numberOfIsland(islandMap);
for(int i =0 ;i< islandMap.length ; i++){
System.out.println(Arrays.toString(islandMap[i]));
}

System.out.println(" number of island : "+ number);
}
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：41841次
• 积分：1624
• 等级：
• 排名：千里之外
• 原创：125篇
• 转载：0篇
• 译文：0篇
• 评论：24条
阅读排行
最新评论