defBFS(sethead, setend): while Qhead != [] and Qend != []: # 一旦某一个队列为空,说明被死亡密码封锁,无法转动到目标密码,跳出循环返回-1 QheadLength = len(Qhead) QendLength = len(Qend) if QheadLength < QendLength: # 队列小的优先扩散,平衡空间复杂度 for i inrange(QheadLength): step = sethead[Qhead[0]] # 转到当前密码所需步数 temp = [] for c in Qhead[0]: temp.append(c) temp = broad(temp) for t in temp: if t in sethead: # 记录以遍历密码,防止重复遍历 continue if t in deadends: # 遇到死亡密码,进行下一个 continue if t in Qhead: # 前有哈希表判断,此条件可以省略 continue sethead[t] = step + 1# 新的密码加入哈希表,步数加1 Qhead.append(t) # 新密码加入队列 if t in setend: return sethead[t] + setend[t] Qhead.pop(0) # 移除所有方向已遍历完成的密码 else: # 结构同上 for i inrange(QendLength): step = setend[Qend[0]] temp = [] for c in Qend[0]: temp.append(c) temp = broad(temp) for t in temp: if t in setend: continue if t in deadends: continue if t in Qend: continue setend[t] = step + 1 Qend.append(t) if t in sethead: return sethead[t] + setend[t] Qend.pop(0) return -1