752. Open the Lock

Medium


You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.



Hints:
SolvingApproachs:

 class Solution:
    def openLock(self, deadends: List[str], target: str) -> int:
#         q = deque()
#         visited = set(deadends)

#         if '0000' in visited:
#             return -1


#         q.append(["0000", 0])


#         def combination(lock):
#             res = []
#             for i in range(4):
#                 num = str((int(lock[i])+1) % 10)
#                 comb = lock[:i] + num + lock[i+1:]
#                 res.append(comb)

#                 num = str((int(lock[i])-1 + 10) % 10)
#                 comb = lock[:i] + num + lock[i+1:]
#                 res.append(comb)

#             return res




#         while q:
#             lock, step = q.popleft()

#             if lock == target:
#                 return step

#             for child in combination(lock):
#                 if child not in visited:
#                     visited.add(child)
#                     q.append([child, step+1])


#         return -1
        q = deque()
        visited = set(deadends)

        if '0000' in visited:
            return -1


        q.append(["0000", 0])


        def combination(lock):
            #res = []
            for i in range(4):
                for operation in (1, -1):

                    num = str((int(lock[i])+ operation + 10) % 10)
                    comb = lock[:i] + num + lock[i+1:]
                    yield comb

        while q:
            lock, step = q.popleft()

            if lock == target:
                return step

            for child in combination(lock):
                if child not in visited:
                    visited.add(child)
                    q.append([child, step+1])


        return -1

Random Note


Need continuous some smaller/larger value? Use heap max or min as you need.