๐ ๐ 200. ๅฒๅฑฟๆฐ้
2022ๅนด6ๆ20ๆฅ
- algorithm
๐ ๐ 200. ๅฒๅฑฟๆฐ้
้พๅบฆ: ๐ ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int numIslands(char[][] grid) {
// ๆ่ทฏ๏ผ
// dfs
int row = grid.length;
int col = grid[0].length;
int res = 0;
// ้ๅๆฐ็ป๏ผ้ๅฐ้ๅฐ๏ผๅฐฑๅฐฝๅฏ่ฝๅฐ็ธ้ป้ๅฐๅ่ฒ๏ผ่กจ็คบๅทฒ็ป้ๅ่ฟ
for(int i = 0; i < row; i ++) {
for(int j = 0; j < col; j ++) {
if(grid[i][j] == '1') {
mySol(grid, i, j);
res ++; // ๅๆฏไธๅๆฐ็้ๅฐ
}
}
}
return res;
}
private void mySol(char[][] grid, int i, int j) {
// ้ๅฝ็ปๆญขๆกไปถ
if(!isValid(grid, i, j)) {
return;
}
if(grid[i][j] != '1') {
return;
}
// ๆ่ฒ
grid[i][j] = '2';
mySol(grid, i + 1, j); // ็ปง็ปญๆ่ฒ
mySol(grid, i - 1, j);
mySol(grid, i, j + 1);
mySol(grid, i, j - 1);
}
private boolean isValid(char[][] grid, int i, int j) {
int row = grid.length;
int col = grid[0].length;
if(i < 0 || j < 0) {
return false;
}
if(i >= row || j >= col) {
return false;
}
return true;
}
}