Skip to content

Instantly share code, notes, and snippets.

@engtomhat
Created August 2, 2017 13:37
Show Gist options
  • Save engtomhat/77034e7204fd3bf87e9c7c0792facaa7 to your computer and use it in GitHub Desktop.
Save engtomhat/77034e7204fd3bf87e9c7c0792facaa7 to your computer and use it in GitHub Desktop.
Number of Islands
public class NumberOfIslands {
public int numIslands(char[][] grid) {
int numOfIslands = 0;
for (int i = 0; i < grid.length; i++) {
char[] row = grid[i];
for (int j = 0; j < row.length; j++) {
if(grid[i][j] == '1') {
numOfIslands++;
scanIsland(grid, i, row, j+1);
scanIsland(grid, i, row, j-1);
scanIsland(grid, i+1, row, j);
scanIsland(grid, i-1, row, j);
}
}
}
return numOfIslands;
}
private void scanIsland(char[][] grid, int yIndex, char[] row, int xIndex) {
if (yIndex >= 0 && yIndex < grid.length && xIndex >= 0 && xIndex < row.length) {
if(grid[yIndex][xIndex] == '1') {
grid[yIndex][xIndex] = '0';
scanIsland(grid, yIndex, row, xIndex+1);
scanIsland(grid, yIndex, row, xIndex-1);
scanIsland(grid, yIndex+1, row, xIndex);
scanIsland(grid, yIndex-1, row, xIndex);
}
}
}
}
Copy link

ghost commented Aug 2, 2017

nice 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment