Leetcode 753 Solution

This article provides solution to leetcode question 753 (open-the-lock)

https://leetcode.com/problems/open-the-lock

Solution

class Solution:
    def openLock(self, deadends: List[str], target: str) -> int:
        deadends_set = {
            (int(deadend[0]), int(deadend[1]), int(deadend[2]), int(deadend[3]))
            for deadend in deadends
        }
        target_lock = (int(target[0]), int(target[1]), int(target[2]), int(target[3]))

        if (0, 0, 0, 0) in deadends_set:
            return -1

        q = collections.deque()
        q.append((0, 0, 0, 0))
        seen = {(0, 0, 0, 0)}

        step = 0
        while q:
            s = len(q)
            for _ in range(s):
                lock = q.popleft()

                if lock == target_lock:
                    return step

                for i in range(4):
                    for delta in [-1, 1]:
                        next_lock = (
                            (lock[0] + delta) % 10 if i == 0 else lock[0],
                            (lock[1] + delta) % 10 if i == 1 else lock[1],
                            (lock[2] + delta) % 10 if i == 2 else lock[2],
                            (lock[3] + delta) % 10 if i == 3 else lock[3],
                        )

                        if next_lock not in deadends_set and next_lock not in seen:
                            q.append(next_lock)
                            seen.add(next_lock)

            step += 1

        return -1