题目链接:https://leetcode-cn.com/problems/number-of-islands/
题目描述
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
第一次编辑代码:
(他写垃圾算法一直可以的)
class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0)
return 0;
int row = grid.length, col = grid[0].length;
int ans = 0;
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++){
if(grid[i][j] == '1'){
dfs(i, j, grid, row, col);
ans++;
}
}
return ans;
}
public void dfs(int i, int j, char[][] grid, int row, int col){
grid[i][j] = '2';
if(i-1 >= 0 && grid[i-1][j] == '1')
dfs(i-1, j, grid, row, col);
if(i+1 < row && grid[i+1][j] == '1')
dfs(i+1, j, grid, row, col);
if(j-1 >= 0 && grid[i][j-1] == '1')
dfs(i, j-1, grid, row, col);
if(j+1 < col && grid[i][j+1] == '1')
dfs(i, j+1, grid, row, col);
}
}
反思
太蠢了,判断条件可以提出来不用重复写。
第二次编辑代码:
class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0)
return 0;
int row = grid.length, col = grid[0].length;
int ans = 0;
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++){
if(grid[i][j] == '1'){
dfs(i, j, grid, row, col);
ans++;
}
}
return ans;
}
public void dfs(int i, int j, char[][] grid, int row, int col){
if(i < 0 || i >= row || j < 0 || j >= col || grid[i][j] != '1')
return;
grid[i][j] = '2';
dfs(i-1, j, grid, row, col);
dfs(i+1, j, grid, row, col);
dfs(i, j-1, grid, row, col);
dfs(i, j+1, grid, row, col);
}
}