其他分享
首页 > 其他分享> > 1905. 统计子岛屿

1905. 统计子岛屿

作者:互联网

遍历grid2,如果在遍历一个岛屿的过程中没有超过相应的grid1的1的范围,说明遍历到了一个子岛屿,否则不是子岛屿

int st[510][510];
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int valid;
class Solution { 
public:
    void dfs(int x, int y, int row, int col, vector<vector<int>>& grid1, vector<vector<int>>& grid2, int &valid){
        st[x][y] = 1;
        if(grid1[x][y] == 0) valid = 0;
        for(int i = 0; i < 4; i ++){
            int a = x + dx[i], b = y + dy[i];
            if(a < 0 || a >= row || b < 0 || b >= col) continue;
            if(grid2[a][b] && !st[a][b]) dfs(a, b, row, col, grid1, grid2, valid);
        }
    }
    
    int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
        memset(st, 0, sizeof st);
        int row = grid1.size(), col = grid1[0].size();
        int cnt = 0;
        for(int i = 0; i < row; i ++){
            for(int j = 0; j < col; j ++){
                if(grid2[i][j] && st[i][j] == 0){
                    valid = 1;
                    dfs(i, j, row, col, grid1, grid2, valid);
                    cnt += valid;
                }
            }
        }

        return cnt;
    }
};

标签:grid1,grid2,int,岛屿,st,valid,1905,统计,row
来源: https://www.cnblogs.com/tomori/p/15172767.html