752. Open the Lock - LeetCode Solution


BFS

Python Code:

class Solution:
    def openLock(self, deadends: List[str], target: str) -> int:
        

        another_deadend = {}

        for i in deadends:
            another_deadend[i] = 1

        queue = []

        visited = {}

        queue.append(["0000", 0])
        visited["0000"] = True

        ans = float("inf")


        while len(queue) !=0:
            k = queue.pop(0)

            if k[0] in another_deadend:
                continue
            if k[0] == target:
                ans = min(ans, k[1])

                break


            for i in range(4):
                str1 = k[0][:i] + str((int(k[0][i]) + 1)%10) + k[0][i+1:]
                str2 = k[0][:i] + str((int(k[0][i]) - 1)%10) + k[0][i+1:]



                if str1 not in visited:
                    visited[str1] = True
                    queue.append([str1, k[1] + 1])

                if str2 not in visited:
                    visited[str2] = True
                    queue.append([str2, k[1] + 1])

        if ans == float("inf"):
            return -1

        return ans


Comments

Submit
0 Comments
More Questions

1585B - Array Eversion
1661C - Water the Trees
1459A - Red-Blue Shuffle
1661B - Getting Zero
1661A - Array Balancing
1649B - Game of Ball Passing
572A - Arrays
1455A - Strange Functions
1566B - MIN-MEX Cut
678C - Joty and Chocolate
1352E - Special Elements
1520E - Arranging The Sheep
1157E - Minimum Array
1661D - Progressions Covering
262A - Roma and Lucky Numbers
1634B - Fortune Telling
1358A - Park Lighting
253C - Text Editor
365B - The Fibonacci Segment
75A - Life Without Zeros
1519A - Red and Blue Beans
466A - Cheap Travel
659E - New Reform
1385B - Restore the Permutation by Merger
706A - Beru-taxi
686A - Free Ice Cream
1358D - The Best Vacation
1620B - Triangles on a Rectangle
999C - Alphabetic Removals
1634C - OKEA