Leetcode 959. DFS+ simulation/merge search of areas divided by slashes

Original title link: Leetcode 959. Divide regions by slashes

insert image description here
insert image description here
insert image description here
Solution 1: Think of a block as a 3x3 matrix, use dfs to determine how many areas there are, refer to:
[C++] [Animation] Convert to the number of islands

class Solution {
    
    
public:
    void dfs(vector<vector<int>>& g,int i,int j,int n)
    {
    
    
        if(i>=0 && i<n*3 && j>=0 && j<n*3 && g[i][j]==0)
        {
    
    
            g[i][j]=1;
            dfs(g,i-1,j,n);
            dfs(g,i+1,j,n);
            dfs(g,i,j-1,n);
            dfs(g,i,j+1,n);
        }
    }
    int regionsBySlashes(vector<string>& grid) {
    
    
        int n=grid.size();
        vector<vector<int>> g(n*3,vector<int>(n*3));
        for(int i=0;i<n;i++)
        {
    
    
            for(int j=0;j<n;j++)
            {
    
    
                if(grid[i][j]=='/')
                {
    
    
                    g[i*3][j*3+2]=g[i*3+1][j*3+1]=g[i*3+2][j*3]=1;
                }
                else if(grid[i][j]=='\\')
                {
    
    
                    g[i*3][j*3]=g[i*3+1][j*3+1]=g[i*3+2][j*3+2]=1;
                }
            }
        }
        int res=0;
        for(int i=0;i<n*3;i++)
        {
    
    
            for(int j=0;j<n*3;j++)
            {
    
    
                if(!g[i][j]) 
                {
    
    
                    dfs(g,i,j,n);
                    res++;
                }
            }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/qq_45791939/article/details/128098418