题解 | #基因变异最小次数#

基因变异最小次数

https://www.nowcoder.com/practice/ca6b659a3fde42c59276c9db98febd94

function minMutation( start ,  end ,  bank ) {
    // write code here
    let hash = new Set()
    let visted = new Set()
    const keys = ["A","C","G","T"]
    for(const k of bank) {
        hash.add(k)
    }
    if(start == end) return 0
    if(!hash.has(end)) return -1
    const queue = [start]
    visted.add(start)
    let step = 1
    while(queue.length) {
        let len = queue.length;
        for(let i=0;i<len;i++) {
            const cur = queue.shift()
            for(let j=0;j<8;j++) {
                for(let k=0;k<4;k++) {
                    if(cur[j] != keys[k]) {
                        const temp = [...cur]
                        temp[j] = keys[k]
                        const next = temp.join("")
                        if(!visted.has(next) && hash.has(next)) {
                            if(next == end) return step
                            visted.add(next)
                            queue.push(next)
                        }
                    }
                }
            }
        }
        step++
    }
    return -1
    
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务