题解 | #开锁#

开锁

http://www.nowcoder.com/practice/e7cbabbf7e0a41ec98055ee5f3d33bbe

bfs,将存在队列中密码的每一位进行操作,直到队列为空或达到目标值,初始时队列和记录已存在的密码集合均为 "0000"

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param vec string字符串一维数组 
# @param tar string字符串 
# @return int整型
#
class Solution:
    def open(self , vec: List[str], tar: str) -> int:
        # write code here
        queue = ["0000"]
        visited = set("0000")
        res = 0
        while queue:
            nxt = []
            for q in queue:
                if q == tar:
                    return res
                if q in vec:
                    continue
                for i in range(4):
                    t = int(q[i])
                    if t == 9:
                        t = 0
                    else:
                        t += 1
                    s = q[:i] + str(t) + q[i + 1:]
                    if s not in vec and s not in visited:
                        visited.add(s)
                        nxt.append(s)
                    t = int(q[i])
                    if t == 0:
                        t = 9
                    else:
                        t -= 1
                    s = q[:i] + str(t) + q[i + 1:]
                    if s not in vec and s not in visited:
                        visited.add(s)
                        nxt.append(s)
            queue = nxt
            res += 1
        return -1
全部评论

相关推荐

我是没经验的毕业生,这啥情况啊会不会是hr在刷kpi
JamesGosli...:字节boss属于是群发了,我都快入职字节了,其他部门还在和我boss打招呼
点赞 评论 收藏
分享
点赞 评论 收藏
分享
Yki_:你要算时间成本呀,研究生两三年,博士三四年,加起来就五六年了,如果你本科去腾讯干五年,多领五年的年薪,加上公司内涨薪,可能到时候十五年总薪资也跟博士差不多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务