This content originally appeared on DEV Community and was authored by Tanuja V
class Solution {
public int closedIsland(int[][] grid) {
int row = grid.length;
int col = grid[0].length;
int countIsland = 0;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if(grid[i][j]==0 && dfs(grid, i, j)){
countIsland++;
}
}
}
return countIsland;
}
boolean dfs(int grid[][], int i, int j){
if(i<0 || j<0 || i>=grid.length || j>=grid[0].length)
return false;
if(grid[i][j]==1 || grid[i][j]==2)
return true;
grid[i][j] = 2;
boolean up = dfs(grid, i+1, j);
boolean down = dfs(grid, i-1, j);
boolean left = dfs(grid, i, j+1);
boolean right = dfs(grid, i, j-1);
return up && down && left && right;
}
}
Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀
If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7
This content originally appeared on DEV Community and was authored by Tanuja V
Tanuja V | Sciencx (2024-06-24T14:43:00+00:00) Number of Closed Islands | LeetCode. Retrieved from https://www.scien.cx/2024/06/24/number-of-closed-islands-leetcode/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.