双端bfs搜索752

752. Open the Lock

破解一个由4位数字组成的锁,数字从0-9,可以顺着转,也可以反着转,从0000开始,求找到密码所转动的最小次数,同时要避开死锁。死锁是每个元素都是4位数组成的数组。

Input: deadends = [“0201”,“0101”,“0102”,“1212”,“2002”], target = “0202”
Output: 6
Explanation:
A sequence of valid moves would be “0000” -> “1000” -> “1100” -> “1200” -> “1201” -> “1202” -> “0202”.
Note that a sequence like “0000” -> “0001” -> “0002” -> “0102” -> “0202” would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end “0102”.

直接用bfs太慢了,时间复杂度是bd,使用双端bfs可以缩短到bd/2(b是结点数,d是每条结点的边数):

  1. 详细介绍:https://www.geeksforgeeks.org/bidirectional-search/
  2. 对0000的4个位置循环进行,每次在队列中加入2个密码,即临边,比如0000的两个邻边是1000和9000,然后是0100和0900…
  3. 重点在每次循环最后的起始结点和终止结点的转变
public int openLock(String[] deadends, String target) {
    Set<String> begin = new HashSet<>();
    Set<String> end = new HashSet<>();
    Set<String> dead = new HashSet<>(Arrays.asList(deadends));

    begin.add("0000");
    end.add(target);
    int count = 0;

    while (!begin.isEmpty() && !end.isEmpty()) {
        Set<String> temp = new HashSet<>();
        for (String s : begin) {
            if (end.contains(s))
                return count;
            if (dead.contains(s))
                continue;
            dead.add(s);
            
            StringBuffer str = new StringBuffer(s);
            for (int i = 0; i < 4; i++) {
                char ch = s.charAt(i);

                String s1 = str.substring(0, i) + (ch == '9'? 0 : ch - '0' + 1) + str.substring(i+1);
                String s2 = str.substring(0, i) + (ch == '0'? 9 : ch - '0' - 1) + str.substring(i+1);

                if (!dead.contains(s1))
                    temp.add(s1);
                if ((!dead.contains(s2)))
                    temp.add(s2);
            }
        }
        //双端bfs算法,从源结点向目标结点搜索,同时从目标结点向源结点搜索
            begin = end;
            end = temp;
            count++;
    }

    return -1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值