AlgoMaster Logo

Open the Lock

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Breadth-First Search (BFS) Approach

Intuition:

To solve the "Open the Lock" problem, we can use a BFS approach. The lock can be represented as a graph where each state (combination of numbers) is a node, and each valid turn of the wheel represents an edge to a new node. BFS is suited here as it explores the shallowest nodes first (minimum number of turns to reach a state).

We initialize a queue starting with the initial lock position ("0000") and attempt to reach the target position while avoiding deadends which act as restricted nodes in our graph.

Steps:

  1. Use a queue to explore node combinations starting from "0000".
  2. Use a set for the deadends to avoid unnecessary processing.
  3. Use a set for visited nodes to prevent revisiting states.
  4. For each move, update each wheel by increasing or decreasing the digit by one.
  5. Count the number of steps taken to reach the target configuration.

Code:

2. Bi-Directional Breadth-First Search (Bi-BFS) Approach

Intuition:

A more efficient way to solve this problem is using bidirectional BFS. Instead of exploring from just the start to the target, we concurrently explore from both directions—the start position and the target position—converging in the middle. This significantly reduces the number of states we need to process.

Steps:

  1. Maintain two queues: one starting from "0000" and one from the target.
  2. Alternate the exploration from each front, ensuring we always process from the smaller queue, optimizing the breadth exploration.
  3. If the two fronts meet, we have found the shortest path.

Code: