原题为:
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
原题地址:https://leetcode.com/problems/number-of-islands/
思路:
应该是深度递归遍历,思路很简单,就是碰到一个值是‘1’的位置,就从这个位置开始扩散遍历,将所有与其相连的值为‘1’的节点染色,染成2,染色之后这整个岛就会变成2;那么在检测新节点时,只要周围(上下左右)节点都不是2,那么它就是一个新的岛。
代码如下:
package leetCode;
public class Solution {
public int numIslands(char[][] grid) {
int res = 0;
if(grid.length==0 || grid[0].length==0){
return 0;
}
int row = grid.length;
int col = grid[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(grid[i][j]=='1'
&&(i-1<0 || grid[i-1][j]!='2')
&&(j-1<0||grid[i][j-1]!='2')
&&(i+1>=row ||grid[i+1][j]!='2')
&&(j+1>=col || grid[i][j+1]!='2')){
res++;
color(grid,i,j);
display(grid);
break;
}
}
}
return res;
}
//从i,j位置开始染色
public void color(char[][] grid,int i,int j){
grid[i][j] = '2';
//上
if(i-1>=0 && grid[i-1][j]=='1'){
color(grid,i-1,j);
}
//下
if(i+1<grid.length && grid[i+1][j]=='1'){
color(grid,i+1,j);
}
//左
if(j-1>=0&&grid[i][j-1]=='1'){
color(grid,i,j-1);
}
//右
if(j+1<grid[0].length&&grid[i][j+1]=='1'){
color(grid,i,j+1);
}
}
public void display(char[][] grid){
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
System.out.print(grid[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
Solution s = new Solution();
//["10111","10101","11101"]
char[][] matrix = {
{'1','0','1','1','1'},
{'1','0','1','0','1'},
{'1','1','1','0','1'}
};
System.out.println(s.numIslands(matrix));
}
}