Created
April 18, 2020 18:23
-
-
Save IngeFrodo/8bfdf0bfdd5f8c4cdf973de4941cad5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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