My C++ code; 9 ms (45 test cases)


  • 4
    Y

    class Solution {
    public:
    int numIslands(vector<vector<char>> &grid) {
    if(grid.size() == 0) return 0;
    const int M = grid.size(), N = grid[0].size();
    int numIsland = 0;

        for(int i=0;i<M;i++)
            for(int j=0;j<N;j++)
                if(grid[i][j] == '1'){
                    numIsland++;
                    dfs(grid,i,j);
                }
        return numIsland;
    }
    
    void dfs(vector<vector<char>> &grid, int row, int col){
        const int M = grid.size(), N = grid[0].size();
        grid[row][col] = '0';
        
        if(row-1>=0 && grid[row-1][col] == '1')
            dfs(grid,row-1,col);
        if(row+1<M && grid[row+1][col] == '1')
            dfs(grid,row+1,col);
        if(col-1>=0 && grid[row][col-1] == '1')
            dfs(grid,row,col-1);
        if(col+1<N && grid[row][col+1] == '1')
            dfs(grid,row,col+1);
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.