代码随想录算法训练营第六十三天—图论补充

第一题、最大岛屿面积 力扣题目链接

class Solution {
private:
    int count;
    int dir[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
    void dfs(vector>& grid, vector>& visited, int x, int y){
        for(int i = 0; i < 4; i++){
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
            if(!visited[nextx][nexty] && grid[nextx][nexty] == 1){
                visited[nextx][nexty] = true;
                count++;
                dfs(grid, visited, nextx, nexty);
            }
        }
    }
public:
    int maxAreaOfIsland(vector>& grid) {
        int n = grid.size(), m = grid[0].size();
        vector> visited = vector>(n, vector(m, false));
        int result = 0;
        for(int i=0; i < n;i++){
            for(int j=0; j < m; j++){
                if(!visited[i][j] && grid[i][j] == 1){
                    count=1;
                    visited[i][j] = true;
                    dfs(grid, visited, i, j);
                    result = max(result, count);
                }
            }
        }
        return result;
    }
};

第二题、飞地数量 力扣题目链接

class Solution {
private:
    int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
    int count;
    void dfs(vector>& grid, int x, int y){
        grid[x][y] = 0;
        count++;
        for(int i=0; i < 4; i++){
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if (nextx < 0 || nextx >= grid.size() || nexty < 0 || nexty >= grid[0].size()) continue;
            if(grid[nextx][nexty] == 0) continue;
            dfs(grid, nextx, nexty);
        }
        return;
    }
public:
    int numEnclaves(vector>& grid) {
        int n = grid.size(), m = grid[0].size();
        // 两边向中间
        for (int i = 0; i < n; i++) {
            if (grid[i][0] == 1) dfs(grid, i, 0);
            if (grid[i][m - 1] == 1) dfs(grid, i, m - 1);
        }
        // 上下向中间
        for (int j = 0; j < m; j++) {
            if (grid[0][j] == 1) dfs(grid, 0, j);
            if (grid[n - 1][j] == 1) dfs(grid, n - 1, j);
        }
        count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1) dfs(grid, i, j);
            }
        }
        return count;
    }
};

你可能感兴趣的:(算法,c++,leetcode,图论,数据结构)