Leetcode Problem 752. Open the Lock

752. Open the Lock

Leetcode Solutions

Breadth-First Search Approach

  1. Initialize a queue and add the initial state '0000'.
  2. Initialize a set to keep track of visited states, including deadends.
  3. If '0000' is in deadends, return -1 immediately.
  4. Perform a BFS, expanding nodes by turning each wheel one digit forward or backward.
  5. For each expanded node, if it's the target, return the number of turns taken to reach it.
  6. If a neighbor has not been visited and is not a deadend, add it to the queue.
  7. If the queue is empty and the target has not been reached, return -1.
UML Thumbnail

Bidirectional Breadth-First Search Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...