DEV Community

Tanuja V
Tanuja V

Posted on

1

Number of Closed Islands | LeetCode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay