Concise C++ Solution 8ms


  • 0
    I
    int numIslands(vector<vector<char>>& grid) {
        int num = 0;
        for(int i = 0; i<grid.size(); i++)
            for(int j = 0; j<grid[0].size(); j++)
                if(grid[i][j] == '1') DFS(grid, i, j, num++);
        return num;
    }
    
    void DFS(vector<vector<char>>& grid, int i, int j, int num){
        if(i == grid.size() || i < 0 || j == grid[0].size() || j < 0 || grid[i][j] != '1') return;
        grid[i][j] = 'a' + num;
        DFS(grid, i+1, j, num);
        DFS(grid, i, j+1, num);
        DFS(grid, i-1, j, num);
        DFS(grid, i, j-1, num);
    }

  • 1
    A

    I think you can define you DFS as

    void DFS(vector<vector<char>>& grid, int i, int j){
        if(i == grid.size() || i < 0 || j == grid[0].size() || j < 0 || grid[i][j] != '1') 
            return;
        grid[i][j] = '0';
        DFS(grid, i+1, j);
        DFS(grid, i, j+1);
        DFS(grid, i-1, j);
        DFS(grid, i, j-1);
    }
    

    No need to pass num as parameter since you don't use it during DFS.


  • 0
    I

    Yes, you are right! Thank you.


Log in to reply
 

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