-
Notifications
You must be signed in to change notification settings - Fork 0
/
752_Open_the_Lock.py
36 lines (28 loc) · 1019 Bytes
/
752_Open_the_Lock.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
34
35
36
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
if '0000' in deadends:
return -1
if target == '0000':
return 0
stack = [target]
length = 1
visit = set()
visit.add(target)
while stack:
cur_stack = []
while stack:
cur = stack.pop(0)
temp = []
for i in range(4):
string = [(ord(cur[i]) - ord('0') + 1) % 10, (ord(cur[i]) - ord('0') - 1) % 10]
for sub_str in string:
temp.append(cur[0:i] + str(sub_str) + cur[i + 1:])
for string in temp:
if not string in deadends and not string in visit:
cur_stack.append(string)
visit.add(string)
if string == '0000':
return length
stack = cur_stack
length += 1
return -1