Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

leetcode每日一题

$
0
0

1162.地图分析

解题思路

此题可以使用广度优先搜索,算法步骤如下:

第一步,先把所有陆地所在位置加入队列,标记为距离0 第二步,每次从队头向外层递推进行BFS,并将搜索到的位置进行标记,并加入下一级搜索队列,距离深度加1 递推公式为 dp(i, j) = dp(i-1, j) + dp(i+1, j)+ dp(i, j-1) + dp(i, j+1)第三步,重复上一步过程,直到队列为空,即所有点都已标记,完成BFS搜索过程,返回深度即为陆地到最远海洋的最近曼哈顿距离

javascript

/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxDistance = function (grid) {

    let store = new Array(grid.length)
    for (let i = 0; i < grid.length; i++) {
        store[i] = new Array(grid[0].length).fill(-1) // 全部坐标距离初始化为-1
    }
    let queue = [], maxDepth = -1,
        directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
    grid.map((row, i) => {
        row.map((pos, j) => {
            if (pos === 1) {
                queue.push([i, j])
                store[i][j] = 0                     // 陆地坐标距离初始化为0
            }
        })
    })

    function isUndiscoveredSea(i, j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {
            return false
        }
        if (store[i][j] >= 0) { // 陆地或已发现海域
            return false
        }
        return true
    }

    if (queue.length == grid.length * grid[0].length) { // 全部为陆地的情况
        return -1
    }

    while (queue.length > 0) {
        maxDepth += 1
        let next = []               // 下一层
        for (let pos of queue) {    // 遍历上一层队列
            for (let direction of directions) {
                let p = pos[0] + direction[0]
                    , q = pos[1] + direction[1]
                if (isUndiscoveredSea(p, q)) { // 未发现海域
                    next.push([p, q])
                    store[p][q] = maxDepth
                }
            }

        }
        queue = next
    }

    return maxDepth
};


Viewing all articles
Browse latest Browse all 14821

Trending Articles