Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abhishek-Chaudhary-InfoCepts/c4ed11776e18921335f9518df2f90b83 to your computer and use it in GitHub Desktop.
Save Abhishek-Chaudhary-InfoCepts/c4ed11776e18921335f9518df2f90b83 to your computer and use it in GitHub Desktop.
class Solution {
public int numIslands(char[][] grid) {
int count =0;
if (grid.length == 0){
return 0;
}
boolean [][] visited = new boolean[grid.length][grid[0].length];
for (int i =0; i < grid.length; i++){
for (int j = 0 ; j < grid[0].length; j++){
if (grid[i][j]=='1' && !visited[i][j]){
count++;
checkPadosiLimitedDirs(grid, i, j, visited);
}
}
}
return count;
}
public void checkPadosiLimitedDirs(char[][] grid, int i, int j, boolean[][] visited){
if (visited[i][j]) {
return;
} else {
visited[i][j] = true;
}
int[] padosi = { -1,1 };
// get x and y offset
for (int x = 0; x < padosi.length; x++) {
int xoffset = padosi[x];
if (validPadosi(grid, i + xoffset, j)) {
checkPadosiLimitedDirs(grid, i + xoffset, j, visited);
}
}
// get x and y offset
for (int y = 0; y < padosi.length; y++) {
int yoffset = padosi[y];
if (validPadosi(grid, i , j+ yoffset)) {
checkPadosiLimitedDirs(grid, i, j+yoffset, visited);
}
}
}
public boolean validPadosi(char[][] grid, int xindex, int yindex){
if ((xindex >= 0 && xindex < grid.length) &&
(yindex >= 0 && yindex < grid[0].length)){
if (grid[xindex][yindex] == '1'){
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment