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

第一题、被围绕的区域 力扣题目链接

class Solution {
private:
    int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
    void dfs(vector>& board, int x, int y){
        board[x][y] = 'A';
        for(int i=0; i < 4; i++){
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if(nextx < 0 || nextx >= board.size() || nexty < 0 || nexty >= board[0].size()) continue;
            if(board[nextx][nexty] == 'X' || board[nextx][nexty] == 'A') continue;
            dfs(board, nextx, nexty);
        }
        return;
    }
public:
    void solve(vector>& board) {
        int n = board.size(), m = board[0].size();
        for(int i=0; i < n; i++){
            if(board[i][0] == 'O') dfs(board, i, 0);
            if(board[i][m-1] == 'O') dfs(board, i, m-1);
        }
        for(int j = 0; j < m; j++){
            if(board[0][j] == 'O') dfs(board, 0, j);
            if(board[n-1][j] == 'O') dfs(board, n-1, j);
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(board[i][j] == 'O') board[i][j] = 'X';
                if(board[i][j] == 'A') board[i][j] = 'O';
            }
        }
    }
};

第二题、太平洋大西洋水流问题 力扣题目链接

class Solution {
private:
    int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};

    void dfs(vector>& heights, vector>& visited, int x, int y){
        if(visited[x][y]) return;
        visited[x][y] = true;
        for (int i = 0; i < 4; i++) { 
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if (nextx < 0 || nextx >= heights.size() || nexty < 0 || nexty >= heights[0].size()){
                continue;
            }  
            if(heights[x][y] > heights[nextx][nexty]) continue;
            dfs(heights, visited, nextx, nexty);
        }
        return;     
    }
public:
    vector> pacificAtlantic(vector>& heights) {
        vector> result;
        int n = heights.size();
        int m = heights[0].size();
        vector> pacific = vector>(n, vector(m, false));
        vector> atlantic = vector>(n, vector(m, false));
        for(int i = 0; i < n;i++){
            dfs(heights, pacific, i, 0);
            dfs(heights,atlantic, i, m-1);
        }
        for (int j = 0; j < m; j++) {
            dfs (heights, pacific, 0, j); 
            dfs (heights, atlantic, n - 1, j); 
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(pacific[i][j] && atlantic[i][j]) result.push_back({i, j});
            }
        }
        return result;
    }
};

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