题目:
给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。
示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:
输入:
11000
11000
00100
00011
输出: 3
AC代码:广度优先
class Solution {
public int numIslands(char[][] grid) {
int row = grid.length;
if(row == 0)
return 0;
int[] x_direct = new int[]{0,1,0,-1};
int[] y_direct = new int[]{1,0,-1,0};
int col = grid[0].length;
Map<Integer,Integer> map = new HashMap<>();
Set<Integer> set = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
for(int i=0;i!=row;++i){
for(int j=0;j!=col;++j){
if(grid[i][j] == '0') continue;
int index = i * col + j;
if(map.containsKey(index)){
continue;
}
//当前内容为陆地
queue.add(index);
map.put(index,index);
grid[i][j] = '0';
while(!queue.isEmpty()){
int deSerialize = queue.remove();
int x_deSerialize = deSerialize / col;
int y_deSerialize = deSerialize % col;
for(int x=0;x!=4;++x){
int temp_x = x_deSerialize + x_direct[x];
int temp_y = y_deSerialize + y_direct[x];
if(temp_x >= 0 && temp_x < row && temp_y >= 0 && temp_y < col && grid[temp_x][temp_y] == '1'){
int temp_index = temp_x * col + temp_y;
queue.add(temp_index);
map.put(temp_index,map.get(deSerialize));
grid[temp_x][temp_y] = '0';
}
}
if(!set.contains(map.get(deSerialize))){
set.add(map.get(deSerialize));
}
}
}
}
return set.size();
}
}