leetcode752. 打开转盘锁 BFS 遍历多叉数

288 阅读1分钟

 你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转:例如把 '9' 变为 '0','0' 变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。

锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。

列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。

字符串 target 代表可以解锁的数字,你需要给出解锁需要的最小旋转次数,如果无论如何不能解锁,返回 -1 。

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/op…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法: bfs 和遍历2叉数类似 这个是个多叉树

/**
 * @param {string[]} deadends
 * @param {string} target
 * @return {number}
 */
var openLock = function(deadends, target) {
    // 其实就是 多叉数遍历
    let queue = ['0000'];
    let visitedSet = new Set();
    let step = 0
    while(queue.length) {
        let cenqueue = queue.length;
        for(let i = 0; i < cenqueue; i++) {
            let node = queue.shift(); // 队列是push和 shift 
            
            if (node == target) {
                return step;
            }
            if (deadends.includes(node)) {
                continue
            }
            if (visitedSet.has(node)) {
                continue
            }

            visitedSet.add(node);
            
            for(let j = 0; j < node.length; j++) {
                // 上升
                let nodelist = node.split('');
                let copy =  node.split('');
                nodelist[j] = ((nodelist[j] == '9') ? '0' : (+nodelist[j] + 1));
                queue.push(nodelist.join(''))
                console.log('nodecopy', nodelist.join(''))
                // 下降
                copy[j] = (node[j] == '0' ? '9' : +node[j] - 1)
                queue.push(copy.join(''))
                // console.log('nodecopy', copy.join(''))
            }
        }
        step++
        console.log('step', queue)
    }
     return -1
};