1.题目
2.解法
①二维数组+DFS
class Solution {
public int numIslands(char[][] grid) {
if(grid.length == 0 || grid[0].length == 0){
return 0;
}
int res = 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'){
res += 1;
dfs(grid, i, j, row, col);
}
}
}
return res;
}
private void dfs(char[][] grid, int x, int y, int row, int col){
if(x < 0 || y < 0 || x >= row || y >= col || grid[x][y] == '0'){
return;
}
grid[x][y] = '0';
dfs(grid, x-1, y, row, col);
dfs(grid, x+1, y, row, col);
dfs(grid, x, y-1, row, col);
dfs(grid, x, y+1, row, col);
}
}
②二维数组,队列+BFS
class Solution {
public int numIslands(char[][] grid) {
if(grid.length == 0 || grid[0].length == 0){
return 0;
}
int res = 0;
int row = grid.length;
int col = grid[0].length;
Queue<List<Integer>> queue = new LinkedList<List<Integer>>();
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(grid[i][j] == '1'){
res += 1;
grid[i][j] = '0';
queue.offer(new ArrayList<Integer>(Arrays.asList(i, j)));
while(queue.size() > 0){
List<Integer> temp = queue.poll();
int x = temp.get(0);
int y = temp.get(1);
if(x - 1 >= 0 && grid[x-1][y] == '1'){
grid[x-1][y] = '0';
queue.offer(new ArrayList<Integer>(Arrays.asList(x-1, y)));
}
if(x + 1 < row && grid[x+1][y] == '1'){
grid[x+1][y] = '0';
queue.offer(new ArrayList<Integer>(Arrays.asList(x+1, y)));
}
if(y - 1 >= 0 && grid[x][y-1] == '1'){
grid[x][y-1] = '0';
queue.offer(new ArrayList<Integer>(Arrays.asList(x, y-1)));
}
if(y + 1 < col && grid[x][y+1] == '1'){
grid[x][y+1] = '0';
queue.offer(new ArrayList<Integer>(Arrays.asList(x, y+1)));
}
}
}
}
}
return res;
}
}