📌  相关文章
📜  大西洋太平洋水流

📅  最后修改于: 2022-05-13 01:57:22.270000             🧑  作者: Mango

大西洋太平洋水流

有一个N x M矩形岛,与太平洋和大西洋接壤。太平洋接触岛屿的左边缘和上边缘,大西洋接触岛屿的右边缘和下边缘。

该岛被划分为方形单元格。岛上降雨量很大,如果相邻单元格的高度小于或等于当前单元格的高度,雨水可以直接向北、南、东、西方向流向相邻的单元格。水可以从与海洋相邻的任何细胞流入海洋。

给定一个矩阵mat[][]NM列,其中mat[x][y]表示坐标(x, y)处单元格的海拔高度,任务是找到坐标(x , y)使得雨水可以从单元(x, y)流向太平洋和大西洋。

例子:

方法:给定的问题可以使用 DFS 或 BFS 遍历来解决。这个想法是使用 DFS 或 BFS 分别标记从太平洋和大西洋直接连接的单元可到达的所有单元。通过两者连接的单元数是必需的答案。以下是要遵循的步骤:

  •  创建两个队列q1q2以便将矩阵的坐标存储为一对。
  • 遍历整个矩阵并将直接连接到太平洋的坐标存储到q1并从q1中的所有坐标执行 BFS 遍历并将它们标记为已访问。
  • 类似地,遍历整个矩阵并将直接连接到大西洋的坐标存储到q2并从q2中的所有坐标执行 BFS 遍历并将它们标记为已访问。
  • 遍历给定的矩阵mat[][]并保持两次遍历期间访问的坐标计数。

下面是上述方法的实现:

C++
// C++ Program of the above approach
#include 
using namespace std;
 
int x[5] = { 0, 0, -1, 1 };
int y[5] = { 1, -1, 0, 0 };
 
// Function to check if coordinate
// (i, j) lies inside N x M matrix
bool safe(int i, int j, int N, int M)
{
    if (i < 0 || j < 0 || i >= N || j >= M)
        return false;
    return true;
}
 
// Function to perform a BFS
// Traversal and mark visited
void BFS(vector > matrix, int N, int M,
         queue > q,
         vector >& vis)
{
    // Loop to traverse q
    while (q.empty() == false) {
        // Stores current coordinate
        pair cur = q.front();
        q.pop();
 
        // Mark current visited
        vis[cur.first][cur.second] = true;
        for (int i = 0; i < 4; i++) {
            int nx = cur.first + x[i];
            int ny = cur.second + y[i];
 
            // If coordinate (nx, ny)
            // is inbound and rechable
            if (safe(nx, ny, N, M)
                && matrix[nx][ny]
                       >= matrix[cur.first]
                                [cur.second]
                && vis[nx][ny] == false) {
                // Insert into queue
                q.push({ nx, ny });
 
                // Mark visited
                vis[nx][ny] = true;
            }
        }
    }
}
 
// Function to find the count of
// valid coordinates
int countCoordinates(vector > mat,
                     int N, int M)
{
    // Queue to perform BFS
    queue > q1, q2;
 
    // Stores the visited coordinates
    // during the 1st traversal
    vector > visited1(
        N,
        vector(M, false));
 
    // Stores the visited coordinates
    // during the 2nd traversal
    vector > visited2(
        N,
        vector(M, false));
 
    // Insert the coordinates
    // directly connected
    for (int i = 0; i < M; i++) {
        q1.push({ 0, i });
        q2.push({ N - 1, i });
    }
    for (int j = 0; j < N - 1; j++) {
        q1.push({ j + 1, 0 });
        q2.push({ j, M - 1 });
    }
 
    // BFS for the 1st ocean
    BFS(mat, N, M, q1, visited1);
 
    // BFS for the 2nd ocean
    BFS(mat, N, M, q2, visited2);
 
    // Stores the required count
    int ans = 0;
 
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            // If coordinate (i, j)
            // is reachable from both
            if (visited1[i][j]
                && visited2[i][j]) {
                // Update count
                ans++;
            }
        }
    }
 
    // Return Answer
    return ans;
}
 
// Driver code
int main()
{
    vector > mat
        = { { 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 } };
 
    cout << countCoordinates(mat, mat.size(),
                             mat[0].size());
    return 0;
}


Python3
Steps = [   
        [-1,0], # Up
        [0,1],  # Right
        [1,0], # bottom
        [0,-1] # Left
    ]
 
def withinLimits(row_num, col_num, total_rows, total_cols):
    if 0 <= row_num < total_rows and 0 <= col_num < total_cols:
        return True
    return False
 
 
def waterSlope(oceanMatrix, matrix, row, col):
    nrows, ncols = len(matrix), len(matrix[0])
    for i in Steps:
        if withinLimits(row+i[0], col+i[1], nrows, ncols):
            if matrix[row+i[0]][col+i[1]] >= matrix[row][col] and not oceanMatrix[row+i[0]][col+i[1]]:
                oceanMatrix[row+i[0]][col+i[1]] = True
                waterSlope(oceanMatrix, matrix, row+i[0], col+i[1])
 
def commonWaterFlow(matrix):
    matrix_rows = len(matrix)
    matrix_cols = len(matrix[0])
    pacificMatrix = [[False for _ in range(matrix_cols)] for _ in range(matrix_rows)]
    atlanticMatrix = [[False for _ in range(matrix_cols)] for _ in range(matrix_rows)]
     
    pacificMatrix[0][1] = True
    pacificMatrix[0][2] = True
     
    for i in range(matrix_cols):
        pacificMatrix[0][i] = True
        atlanticMatrix[matrix_rows-1][i] = True
     
    for i in range(matrix_rows):
        pacificMatrix[i][0] = True
        atlanticMatrix[i][matrix_cols-1] = True
     
    for i in range(matrix_cols):
        waterSlope(pacificMatrix, matrix, 0, i)
        waterSlope(atlanticMatrix, matrix, matrix_rows-1, i)
     
    for i in range(matrix_rows):
        waterSlope(pacificMatrix, matrix, i, 0)
        waterSlope(atlanticMatrix, matrix, i, matrix_cols-1)
     
    Count = 0
     
    for i in range(matrix_rows):
        for j in range(matrix_cols):
            if pacificMatrix[i][j] and atlanticMatrix[i][j]:
                Count += 1
     
    return Count
 
mat = [ [ 1, 2, 2, 3, 5 ],  # T-T-T-T-T     F-F-F-F-T
        [ 3, 2, 3, 4, 4 ],  # T-T-T-T-T     F-F-F-T-T
        [ 2, 4, 5, 3, 1 ],  # T-T-T-F-F     F-F-T-T-T
        [ 6, 7, 1, 4, 5 ],  # T-T-F-F-F     T-T-T-T-T
        [ 5, 1, 1, 2, 4 ] ] # T-F-F-F-F     T-T-T-T-T
print(commonWaterFlow(mat))



输出
7

时间复杂度: O(N*M)
辅助空间: O(N*M)