-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17-Hack.py
More file actions
23 lines (20 loc) · 694 Bytes
/
Copy path17-Hack.py
File metadata and controls
23 lines (20 loc) · 694 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from collections import deque
def openLock(self, deadends: List[str], target: str) -> int:
dead=set(deadends)
def neighbor(code):
for i in range(4):
digit=int(code[i])
for j in (-1,1):
next_digit=(digit+j)%10
yield code[:i]+str(next_digit)+code[i+1:]
q=deque([('0000',0)])
vis={'0000'}
while q:
code, step=q.popleft()
if code == target: return step
if code not in dead:
for nei in neighbor(code):
if nei not in vis and nei not in dead:
q.append((nei,step+1))
vis.add((nei))
return -1