forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
33 lines (32 loc) · 973 Bytes
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
def next(s):
res = []
s = list(s)
for i in range(4):
c = s[i]
s[i] = '9' if c == '0' else str(int(c) - 1)
res.append(''.join(s))
s[i] = '0' if c == '9' else str(int(c) + 1)
res.append(''.join(s))
s[i] = c
return res
if target == '0000':
return 0
s = set(deadends)
if '0000' in s:
return -1
q = deque([('0000')])
s.add('0000')
ans = 0
while q:
ans += 1
for _ in range(len(q)):
p = q.popleft()
for t in next(p):
if t == target:
return ans
if t not in s:
q.append(t)
s.add(t)
return -1