Skip to content

Instantly share code, notes, and snippets.

@IngeFrodo
Created April 18, 2020 18:23
Show Gist options
  • Save IngeFrodo/8bfdf0bfdd5f8c4cdf973de4941cad5a to your computer and use it in GitHub Desktop.
Save IngeFrodo/8bfdf0bfdd5f8c4cdf973de4941cad5a to your computer and use it in GitHub Desktop.
class NumberOfIslands {
public int numIslands(char[][] grid) {
int numIslands = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == '1') {
dfs(grid, r, c);
numIslands++;
}
}
}
return numIslands;
}
private void dfs(char[][] grid, int row, int col) {
if (row < 0 || row >= grid.length
|| col < 0 || col >= grid[row].length
|| grid[row][col] == '0') {
return;
}
grid[row][col] = '0';
dfs(grid, row - 1, col);
dfs(grid, row, col + 1);
dfs(grid, row + 1, col);
dfs(grid, row, col - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment