0% found this document useful (0 votes)
22 views1 page

DFS - Deep First Search

The document describes a depth-first search (DFS) algorithm to count the number of islands in a 2D grid. The algorithm uses DFS to mark all cells in each island as visited. It iterates through the grid and counts an island each time it finds an unvisited '1' cell, calling DFS on that cell.

Uploaded by

Arn Silv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views1 page

DFS - Deep First Search

The document describes a depth-first search (DFS) algorithm to count the number of islands in a 2D grid. The algorithm uses DFS to mark all cells in each island as visited. It iterates through the grid and counts an island each time it finds an unvisited '1' cell, calling DFS on that cell.

Uploaded by

Arn Silv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solution {

private:
        void dfs(vector<vector<char>>& grid, int r, int c)
    {
                int nr = grid.size();
                int nc = grid[0].size();
        
                grid[r][c] = '0';
                if (r-1>=0 && grid[r-1][c] == '1') dfs(grid, r-1, c);
                if (r+1<=nr-1 && grid[r+1][c] == '1') dfs(grid, r+1, c);
                if (c-1>=0 && grid[r][c-1] == '1') dfs(grid, r, c-1);
                if (c+1<=nc-1 && grid[r][c+1] == '1') dfs(grid, r, c+1);
        
    }
    
public:
        int numIslands(vector<vector<char>>& grid) {
                int nr = grid.size();
                if (!nr) return 0;
                int nc = grid[0].size();
                int num_islands = 0;
        
                for (int r = 0; r != nr; r++)
        {
                        for (int c = 0; c != nc; c++)
            {
                                if (grid[r][c] == '1')
                {
                                        dfs(grid, r ,c);
                                        num_islands++;
                }
            }
        }
        
                return num_islands;
        
    }
};

You might also like