Created
August 2, 2017 13:37
-
-
Save engtomhat/77034e7204fd3bf87e9c7c0792facaa7 to your computer and use it in GitHub Desktop.
Number of Islands
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
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); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice 👍