Skip to content

Instantly share code, notes, and snippets.

@marttp
Created December 29, 2024 06:37
Show Gist options
  • Save marttp/2e89aadd35b0e6d314723e74160e56e4 to your computer and use it in GitHub Desktop.
Save marttp/2e89aadd35b0e6d314723e74160e56e4 to your computer and use it in GitHub Desktop.
class Solution {
private static final int[][] DIRS = new int[][] {
new int[] {-1,0},
new int[] {1,0},
new int[] {0,-1},
new int[] {0,1}
};
public int numIslands(char[][] grid) {
int ans = 0;
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == '1') {
ans++;
markWater(grid, r, c);
}
}
}
return ans;
}
private void markWater(char[][] grid, int r, int c) {
if (isInbound(grid, r, c) && grid[r][c] != '0') {
grid[r][c] = '0';
for (var dir : DIRS) {
markWater(grid, r + dir[0], c + dir[1]);
}
}
}
private boolean isInbound(char[][] grid, int r, int c) {
return r >= 0 && r < grid.length && c >= 0 && c < grid[r].length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment