We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f3c53d5 commit 5ebd76cCopy full SHA for 5ebd76c
752-Open-the-Lock.py
@@ -0,0 +1,26 @@
1
+class Solution:
2
+ def openLock(self, deadends: List[str], target: str) -> int:
3
+ if "0000" in deadends:
4
+ return -1
5
+
6
+ def children(wheel):
7
+ res = []
8
+ for i in range(4):
9
+ digit = str((int(wheel[i]) + 1) % 10)
10
+ res.append(wheel[:i] + digit + wheel[i+1:])
11
+ digit = str((int(wheel[i]) + 10 - 1) % 10)
12
13
+ return res
14
15
+ q = deque()
16
+ visit = set(deadends)
17
+ q.append(["0000", 0]) # [wheel, turns]
18
+ while q:
19
+ wheel, turns = q.popleft()
20
+ if wheel == target:
21
+ return turns
22
+ for child in children(wheel):
23
+ if child not in visit:
24
+ visit.add(child)
25
+ q.append([child, turns + 1])
26
0 commit comments