老師幫我看下這個報錯

来源:9-4 LeetCode:417. 太平洋大西洋水流问题

weixin_慕雪0272820

2021-06-17

/**
 * @param {number[][]} heights
 * @return {number[][]}
 */
var pacificAtlantic = function(heights) {
    //如果二維陣列不存在返回
    if(!heights || !heights[0]) return []

    const m = heights.length
    const n = heights[0].length
    
    //二維陣列創法
    const flow1 = Array.from({length:m}, ()=>{new Array(n).fill(false)})
    const flow2 = Array.from({length:m}, ()=>{new Array(n).fill(false)})

    const dfs = (r,c, flow) => {
        flow[r][c] = true
        [[r+1, c],[r-1, c], [r,c+1],[r, c-1]].forEach(([nr,nc]) => {
            if(nr>=0 && nr < m && nc>=0 && nc<n &&
            //防止死循環
            !flow[nr][nc]&&
            //保證逆流而上
            heights[nr][nc] >= heights[n][c]
            )
            dfs(nc,nr, flow)
        })
    }

    //沿著海岸線開始圖的深度遍歷
    for(let i = 0; i< m ; i++){
        dfs(i, 0 , flow1)
        dfs(i,n-1, flow2 )
    }

    for(let i =0; i<n; i++){
        dfs(0, i ,flow1)
        dfs(m-1, i ,flow2)
    }

    let res = []
    for(let i =0 ; i <m ; i++){
        for(let j =0 ; j < n; j++){
            if(flow1[i][j] && flow2[i][j]){
                res.push([r,c])
            }
        }
    }

    return res
};

图片描述

是哪裡有問題呢? 我看 [[r+1, c],[r-1, c], [r,c+1],[r, c-1]]有值呀

写回答

4回答

momo_已黑化

2023-04-04

我也犯了这个错误!我在递归中把nr和nc写反了自己找了好久的问题 发现其实是进了死循环 改过来就好了

0
0

teaper

2022-09-07

flow[r][c] = true

后面加上分号

0
0

徐一刀

2021-09-13

new array哪里多加了{}

0
0

lewis

2021-06-18

确实很诡异,要不你打印一下你构造的数组

0
4
lewis
回复
weixin_慕雪0272820
如果有值的话,确实不应该为undefined,你在每个循环都打log,看下undefined究竟出现在哪里
2021-06-23
共4条回复

JavaScript版数据结构与算法 轻松解决前端算法面试

夯实算法基础,填补技术短板,助力面试考题最后一公里

2481 学习 · 683 问题

查看课程