From 5a7cf2a5706afa15ffb9bfd4ee2dc8588d679609 Mon Sep 17 00:00:00 2001 From: Azureki Date: Sat, 13 Oct 2018 09:56:32 +0800 Subject: [PATCH] BFS --- lc752. Open the Lock.py | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 lc752. Open the Lock.py diff --git a/lc752. Open the Lock.py b/lc752. Open the Lock.py new file mode 100644 index 0000000..7413054 --- /dev/null +++ b/lc752. Open the Lock.py @@ -0,0 +1,42 @@ +class Solution: + def openLock(self, deadends, target): + """ + :type deadends: List[str] + :type target: str + :rtype: int + """ + deadset = set(deadends) + if '0000' in deadset: + return -1 + import queue + setps = 0 + q = queue.Queue() + q.put('0000') + visited = {'0000'} + + while not q.empty(): + setps += 1 + length = q.qsize() + for _ in range(length): + + node = q.get() + + for i in range(4): + for j in (-1, 1): + slst = list(node) + slst[i] = str((int(slst[i]) + j) % 10) + tem = ''.join(slst) + if tem == target: + return setps + if tem not in visited and tem not in deadset: + q.put(tem) + visited.add(tem) + + return -1 + + +deadends = ["0000"] +target = "8888" +s = Solution() + +print(s.openLock(deadends, target))