题解 | #检测循环依赖#

检测循环依赖

https://www.nowcoder.com/practice/8dc02ad98553432a90affc3a0484910b

function findOrder( prerequisites ,  n ) {
    // write code here
    // 构建图
    const res = []
    let hasCycle = false
    const path = new Array(n).fill(false)
    const visted = new Array(n).fill(false)
    const buildGraph = (prerequisites,n) => {
        const graph = new Array(n).fill(null).map(()=>new Array())
        for(let i=0;i<prerequisites.length;i++) {
            const edge = prerequisites[i]
            const from = edge[1],to = edge[0]
            graph[from].push(to)
        }
        return graph
    }
    const traverse = (graph,v) => {
        if(path[v]) hasCycle = true
        if(visted[v] || hasCycle) return 
        visted[v] = true
        path[v] = true
        for(const w of graph[v]) {
            traverse(graph,w)
        }
        res.push(v)
        path[v] = false
    }
    const graph = buildGraph(prerequisites,n)
    for(let i=0;i<n;i++) {
        traverse(graph,i)
    }
    if(hasCycle) return []
    res.reverse()
    return res
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务