Straightforward C++ DFS and BFS


  • 0

    DFS:

        int row, col;
        
        int numIslands(vector<vector<char>>& grid) {
            int nLand = 0;
            row = grid.size(); 
            col = row? grid[0].size() : 0;
           
            for (int i = 0; i < row; ++i)
                for (int j = 0; j < col; ++j)
                    if (grid[i][j] == '1') {
                        ++nLand;
                        dfs(grid, i, j);
                    }
            return nLand;
        }
        
        void dfs(vector<vector<char>>& grid, int i, int j) {
            if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == '0') 
                return;        
            grid[i][j] = '0';
            dfs(grid, i-1, j); 
            dfs(grid, i+1, j); 
            dfs(grid, i, j-1);
            dfs(grid, i, j+1);
        }
    

    BFS:

        int row, col;
        
        int numIslands(vector<vector<char>>& grid) {
            int nLand = 0;
            row = grid.size();
            col = row? grid[0].size() : 0;
            
            for (int i = 0; i < row; ++i)
                for (int j = 0; j < col; ++j)
                    if (grid[i][j] == '1') {
                        ++nLand;
                        bfs(grid, i, j);
                    }
            return nLand;
        }
        
        void bfs(vector<vector<char>>& grid, int i, int j) {
            queue<pair<int, int>> q;
            for (grid[i][j] = '0', q.emplace(i, j); !q.empty(); q.pop()) {
                i = q.front().first, j = q.front().second;
                if (i > 0     && grid[i-1][j] == '1') q.emplace(i-1, j), grid[i-1][j] = '0';
                if (i+1 < row && grid[i+1][j] == '1') q.emplace(i+1, j), grid[i+1][j] = '0';
                if (j > 0     && grid[i][j-1] == '1') q.emplace(i, j-1), grid[i][j-1] = '0';
                if (j+1 < col && grid[i][j+1] == '1') q.emplace(i, j+1), grid[i][j+1] = '0';
            }
        }
    

Log in to reply
 

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