Google Interview - Flowing Water

Given a N*N matrix contains lakes, each lake is represented by an elevation. The water in each lake can flow to its neighbours which has lower or equal elevations.

Suppose the left and top side of the matrix is surrounded by Pacific, the right and bottom is Atlantic.

Please write a function and return all lakes that can flow to both Pacific and Atlantic.

For example:

Pacific: ~
Atlantic: *

~  ~   ~   ~   ~   ~  ~
~  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  *
*  *   *   *   *   *  *

The elements in parentheses are expected outputs:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]]

/*
struct Point {
    int x{ 0 }, y{ 0 };
};
*/
vector<vector<int>> dirs = {{0,1}, {0,-1}, {1,0}, {-1,0}};
void dfs(vector<vector<int>>& mat, unordered_set<Point>& ocean, Point p) {
    int n = mat.size();
    ocean.insert(p);
    for(auto& dir:dirs) {
        int x = p.x+dir[0];
        int y = p.y+dir[1];
        if(x<0 || y<0 || x>=n || y>=n || mat[x][y]<mat[p.x][p.y] || ocean.count({x,y})) continue;
        dfs(mat, ocean, {x,y});
    }
}
vector<Point> flowing_water(vector<vector<int>>& mat) {
    unordered_set<Point> pac, atl;
    int n = mat.size();
    for(int i=0; i<n; i++) {
        dfs(mat, pac, {0, i});
        dfs(mat, pac, {i, 0});
        dfs(mat, atl, {n-1, i});
        dfs(mat, atl, {i, n-1});
    }
    vector<Point> res;
    // unordered results
    // for(auto& p:atl) {
    //     if(pac.count(p)) {
    //         res.push_back(p);
    //     }
    // }
    
    // ordered results
    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
            Point p = {i, j};
            if(pac.count(p) && atl.count(p)) {
                res.push_back(p);
            }
        }
    }
    return res;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2219621