Skip to content

Commit 5ebd76c

Browse files
authored
Create 752-Open-the-Lock.py
1 parent f3c53d5 commit 5ebd76c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

752-Open-the-Lock.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
res.append(wheel[:i] + digit + wheel[i+1:])
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+
return -1

0 commit comments

Comments
 (0)