给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] 的值为 '0' 或 '1'
public void dfs(char[][] grid,int row,int column){
int rowLength = grid.length;
int columnLength = grid[0].length;
if(row >= rowLength || column >= columnLength || row < 0 || column < 0 || grid[row][column] == '0'){
return;
}
grid[row][column] = '0';
dfs(grid,row - 1,column);
dfs(grid,row + 1,column);
dfs(grid,row,column + 1);
dfs(grid,row,column - 1);
}
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0){
return -1;
}
int rowLength = grid.length;
int columnLength = grid[0].length;
int count = 0;
for(int row = 0; row < rowLength; row++){
for(int column = 0; column < columnLength; column++){
if(grid[row][column] == '1'){
count++;
}
dfs(grid,row,column);
}
}
return count;
}
a b c 三个数,需要将ab组合后再分离
组合:a*c + b
分离:(a*c + b)/c = a + 0
(a*c + b)%c = 0 + b
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0){
return 0;
}
int rowLength = grid.length;
int columnLength = grid[0].length;
int count = 0;
for(int row = 0; row < rowLength; row++){
for(int column = 0; column < columnLength; column++) {
if (grid[row][column] == '1') {
count++;
grid[row][column] = '0';
Queue<Integer> roundLand = new LinkedList<>();
roundLand.add(row * columnLength + column);
while (!roundLand.isEmpty()) {
int location = roundLand.remove();
int curRow = location / columnLength;
int curCol = location % columnLength;
if (curRow - 1 >= 0 && grid[curRow - 1][curCol] == '1') {
roundLand.add((curRow - 1) * columnLength + curCol);
grid[curRow - 1][curCol] = '0';
}
if (curRow + 1 < rowLength && grid[curRow + 1][curCol] == '1') {
roundLand.add((curRow + 1) * columnLength + curCol);
grid[curRow + 1][curCol] = '0';
}
if (curCol - 1 >= 0 && grid[curRow][curCol - 1] == '1') {
roundLand.add(curRow * columnLength + curCol - 1);
grid[curRow][curCol - 1] = '0';
}
if (curCol + 1 < columnLength && grid[curRow][curCol + 1] == '1') {
roundLand.add(curRow * columnLength + curCol + 1);
grid[curRow][curCol + 1] = '0';
}
}
}
}
}
return count;
}
时间复杂度:O(MN),其中 MM 和 NN 分别为行数和列数。
空间复杂度:O(min(M,N)),在最坏情况下,整个网格均为陆地,队列的大小可以达到 min(M,N)