Leetcode 200 Number of Islands Solution in c++ | Hindi Coding Community

0


  Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.


class Solution {
public:
    bool isValid(int i,int j,int n,int m,vector<vector<char>>& grid){
        if(i>=0 && j>=0 && i<n && j<m && grid[i][j]=='1')
            return true;
        return false;
    }
    void dfs(int i,int j,int n,int m,vector<vector<char>>& grid){
        grid[i][j]='0';
        if(isValid(i-1,j,n,m,grid))
            dfs(i-1,j,n,m,grid);
        if(isValid(i+1,j,n,m,grid))
            dfs(i+1,j,n,m,grid);
        if(isValid(i,j-1,n,m,grid))
            dfs(i,j-1,n,m,grid);
        if(isValid(i,j+1,n,m,grid))
            dfs(i,j+1,n,m,grid);

    }
    int numIslands(vector<vector<char>>& grid) {
        int n=grid.size();
        int m=grid[0].size();
        int ans=0;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(grid[i][j]=='1'){
                    ans++;
                    dfs(i,j,n,m,grid);
                }
            }
        }
        return ans;
    }
};



Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !