算法笔记28:太平洋大西洋水流问题

146 阅读1分钟

417. 太平洋大西洋水流问题

按照正向思路去思考,是会超时的。因为如果对每一个坐标进行是否能够流动的搜索,要操作的元素很多,复杂度比较高。此时可以反向思考,从结尾处进行搜索,也就是从入海口处(边缘坐标)开始。只不过,再往下搜索的条件就是和原来相反的,原来题目是海拔从高到低,这时就要从低到高。

代码如下:

const pacificAtlantic = (heights) => {
    const m = heights.length;
    const n = heights[0].length;
    
    // two matrix to store the info
    const pacific = Array(m).fill(null).map(() => Array(n).fill(false));
    const atlantic = Array(m).fill(null).map(() => Array(n).fill(false));
    
    var dfs = (i, j, matrix) => {
        // if dfs reaches this coordinate, set it to true
        matrix[i][j] = true;
        
        const neighbors = [
            [i - 1, j],
            [i + 1, j],
            [i, j - 1],
            [i, j + 1],
        ];
        neighbors.forEach(([ni, nj]) => {
            if (
                // make sure indexes are in the boundary
                ni >= 0 && nj >= 0 &&
                ni < m  && nj < n &&
                // do not go into places already available
                !matrix[ni][nj] &&
                // the condition mentioned in the problem, yet reversed
                heights[i][j] <= heights[ni][nj]
            ) {
                dfs(ni, nj, matrix);
            }
        });
    }
    
    // do the search for each edge accordingly
    for (let r = 0; r < m; r++) {
        dfs(r, 0, pacific);
        dfs(r, n - 1, atlantic);
    }
    for (let c = 0; c < n; c++) {
        dfs(0, c, pacific);
        dfs(m - 1, c, atlantic);
    }
    
    const res = [];
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            // the coordinates has both true values is the answer
            if (pacific[i][j] && atlantic[i][j]) {
                res.push([i, j]);
            }
        }
    }
    return res;
};