美文网首页
Pacific Atlantic Water Flow

Pacific Atlantic Water Flow

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-05-22 15:46 被阅读12次

题目来源
一个矩阵,水能从高往低流,左边上边是太平洋,右边下边是大西洋,问哪些地方既可以流往太平洋,又能够流往大西洋。
我用dfs的方法来做,但是写起来还是挺烦人的,感觉应该会有更好的更简洁的方法,代码如下:

class Solution {
public:
    vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {
        int n = matrix.size();
        vector<pair<int, int>> res;
        if (n == 0)
            return res;
        int m = matrix[0].size();
        vector<vector<pair<int, int>>> closePA(n, vector<pair<int, int>>(m, make_pair(0, 0)));
        for (int i=0; i<m; i++) {
            if (closePA[0][i].first < 1) {
                closePA[0][i].first = 1;
                dfs(0, i, matrix, closePA);
            }
            if (closePA[n-1][i].second < 1) {
                closePA[n-1][i].second = 1;
                dfs(n-1, i, matrix, closePA);
            }
        }
        for (int i=0; i<n; i++) {
            if (closePA[i][0].first < 1) {
                closePA[i][0].first = 1;
                dfs(i, 0, matrix, closePA);
            }
            if (closePA[i][m-1].second < 1) {
                closePA[i][m-1].second = 1;
                dfs(i, m-1, matrix, closePA);
            }
        }
        for (int i=0; i<n; i++)
            for (int j=0; j<m; j++) {
                if (closePA[i][j] == make_pair(1, 1))
                    res.push_back(make_pair(i, j));
            }
        return res;
    }
    
    void dfs(int row, int col, vector<vector<int>>& matrix, vector<vector<pair<int, int>>>& closePA)
    {
        for (int i=0; i<dirs.size(); i++) {
            int newRow = row + dirs[i].first, newCol = col + dirs[i].second;
            if (newRow >= 0 && newRow < matrix.size() && newCol >= 0 && newCol < matrix[0].size() && 
                matrix[newRow][newCol] >= matrix[row][col] && 
                (closePA[newRow][newCol].first < closePA[row][col].first || 
                closePA[newRow][newCol].second < closePA[row][col].second)) {
                closePA[newRow][newCol].first = max(closePA[newRow][newCol].first, closePA[row][col].first);
                closePA[newRow][newCol].second = max(closePA[newRow][newCol].second, closePA[row][col].second);
                dfs (newRow, newCol, matrix, closePA);
            }
        }
    }
};

相关文章

网友评论

      本文标题:Pacific Atlantic Water Flow

      本文链接:https://www.haomeiwen.com/subject/mqabxxtx.html