Skip to content

Commit

Permalink
BFS
Browse files Browse the repository at this point in the history
  • Loading branch information
rinwf committed Oct 13, 2018
1 parent 6cba288 commit 5a7cf2a
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions lc752. Open the Lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
class Solution:
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
deadset = set(deadends)
if '0000' in deadset:
return -1
import queue
setps = 0
q = queue.Queue()
q.put('0000')
visited = {'0000'}

while not q.empty():
setps += 1
length = q.qsize()
for _ in range(length):

node = q.get()

for i in range(4):
for j in (-1, 1):
slst = list(node)
slst[i] = str((int(slst[i]) + j) % 10)
tem = ''.join(slst)
if tem == target:
return setps
if tem not in visited and tem not in deadset:
q.put(tem)
visited.add(tem)

return -1


deadends = ["0000"]
target = "8888"
s = Solution()

print(s.openLock(deadends, target))

0 comments on commit 5a7cf2a

Please sign in to comment.