【力扣】太平洋大西洋水流問題-規定水流只能按照上、下、左、右四個方向流動,且只能從高到低或者在同等高度上流動。 請找出那些水流既可以流動到“太平洋”,又能流動到“大西洋”的陸地單元的座標

417. 太平洋大西洋水流問題

給定一個 m x n 的非負整數矩陣來表示一片大陸上各個單元格的高度。“太平洋”處於大陸的左邊界和上邊界,而“大西洋”處於大陸的右邊界和下邊界。
規定水流只能按照上、下、左、右四個方向流動,且只能從高到低或者在同等高度上流動。
請找出那些水流既可以流動到“太平洋”,又能流動到“大西洋”的陸地單元的座標。
提示:
輸出座標的順序不重要
m 和 n 都小於150

示例:

給定下面的 5x5 矩陣:

太平洋 ~ ~ ~ ~ ~
1 2 2 3 (5) *
3 2 3 (4) (4) *
2 4 (5) 3 1 *
(6) (7) 1 4 5 *
(5) 1 1 2 4 *
          • 大西洋
            返回:
            [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上圖中帶括號的單元).

代碼

使用深度優先遍歷

class Solution {
public:
	//注意一下  在這塊傳參時vector<vector<int>> &matrix,這塊使用引用,不然力扣會判超時。題不難但是我看了好久,就是因爲這個超時。
    void dfs(vector<vector<int>> &matrix,int row,int col ,int height, vector<vector<int>>& tag) {
        int R = matrix.size(), C = matrix[0].size();
        if ( row<0||col < 0 || row >= R || col >= C || tag[row][col] == 1 || matrix[row][col] < height)return;
        tag[row][col] = 1;
        dfs(matrix, row - 1, col, matrix[row][col], tag);
        dfs(matrix, row, col - 1, matrix[row][col], tag);
        dfs(matrix, row + 1, col, matrix[row][col], tag);
        dfs(matrix, row, col + 1, matrix[row][col], tag);

    }
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {
        if (matrix.empty())return {};
        vector<vector<int>>res;
        int R = matrix.size(), C = matrix[0].size();
        vector<vector<int>>pacific_tag(R, vector<int>(C, 0));//太平洋標籤矩陣
        vector<vector<int>>atlantic_tag(R, vector<int>(C, 0));//大西洋標籤矩陣
        //左右邊界
        for (int i = 0; i < R; ++i) {
            dfs(matrix, i, 0, matrix[i][0], pacific_tag);
            dfs(matrix, i, C-1, matrix[i][C - 1], atlantic_tag);
        }
        //上下邊界
        for (int j = 0; j < C; ++j) {
            dfs(matrix, 0, j, matrix[0][j], pacific_tag);
            dfs(matrix, R-1,j, matrix[R - 1][j], atlantic_tag);
        }
        for (int i = 0; i < R; ++i) {
            for (int j = 0; j < C; ++j) {
                if (pacific_tag[i][j] == 1 && atlantic_tag[i][j] == 1)
                    res.push_back({ i,j });
            }
        }
        //myprint2(res);
        return res;
    }
};

測試用例:

int main() {
    vector<vector<int>>vec = { {1,2,2,3,5} ,{3,2,3,4,4} ,{2,4,5,3,1},{6,7,1,4,5},{5,1,1,2,4} };
    Solution S;
    //vector<vector<int>>vec1(0, vector<int>(0));
    S.pacificAtlantic(vec);
    return 0;
}

結果:[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章