Detailed explanation coming soon!
/*
* Explore the island and delete the parts we have explored while exploring
* Therefore every '1' we hit must be a new island
*/
class Solution {
public int numIslands(char[][] grid) {
int rows = grid.length;
if (rows == 0) return 0;
int cols = grid[0].length;
int islands = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (grid[row][col] == '1') {
updateGrid(grid, row, col);
islands++;
}
}
}
return islands;
}
public static void updateGrid(char[][] grid, int row, int col) {
int rows = grid.length;
int cols = grid[0].length;
if (!isWithinBounds(grid, row, col) || grid[row][col] == '0') return;
grid[row][col] = '0';
updateGrid(grid, row, col + 1);
updateGrid(grid, row + 1, col);
updateGrid(grid, row, col - 1);
updateGrid(grid, row - 1, col);
}
public static boolean isWithinBounds(char[][] grid, int row, int col) {
return
grid.length > 0 &&
row >= 0 &&
col >= 0 &&
row < grid.length &&
col < grid[0].length;
}
}
Questions? Have a neat solution? Comment below!