Algo-Sim › Graph Traversal

Open the Lock

Medium · Graph Traversal · step through it in Java, Python and C++ on your own input

BFS over the 10,000 lock combinations: each has 8 neighbours one click away, and deadends are marked seen before the search starts.

Problem

A lock has 4 wheels with digits 0–9; one move turns one wheel one click up or down, wrapping between 9 and 0. It starts at "0000". The lock jams if it ever shows a combination in deadends. Return the fewest moves to reach target, or -1 if it cannot be done.

Constraints

Edge cases to test

Follow-up questions

Why is BFS enough?
Every move costs 1, so the first time BFS reaches the target is the fewest moves: O(10⁴ · 8).
How do you speed it up?
Bidirectional BFS from both ends, or A* with the sum of per-wheel circular distances as the heuristic.

Solution

Java

public int openLock(String[] deadends, String target) {
    Set<String> seen = new HashSet<>(Arrays.asList(deadends));
    if (seen.contains("0000")) return -1;
    Queue<String> queue = new ArrayDeque<>(List.of("0000"));
    seen.add("0000");
    for (int turns = 0; !queue.isEmpty(); turns++) {
        for (int size = queue.size(); size > 0; size--) {
            String lock = queue.poll();
            if (lock.equals(target)) return turns;
            for (String next : neighbours(lock)) {
                if (seen.add(next)) queue.offer(next);
            }
        }
    }
    return -1;
}

// The 8 combinations one click away: each wheel turned up or down.
private List<String> neighbours(String lock) {
    List<String> out = new ArrayList<>();
    char[] c = lock.toCharArray();
    for (int i = 0; i < 4; i++) {
        char original = c[i];
        c[i] = original == '9' ? '0' : (char) (original + 1);
        out.add(new String(c));
        c[i] = original == '0' ? '9' : (char) (original - 1);
        out.add(new String(c));
        c[i] = original;
    }
    return out;
}

Python

from collections import deque


def open_lock(deadends, target):
    seen = set(deadends)
    if "0000" in seen:
        return -1
    queue = deque(["0000"])
    seen.add("0000")
    turns = 0
    while queue:
        for _ in range(len(queue)):
            lock = queue.popleft()
            if lock == target:
                return turns
            for nxt in neighbours(lock):
                if nxt not in seen:
                    seen.add(nxt)
                    queue.append(nxt)
        turns += 1
    return -1


# The 8 combinations one click away: each wheel turned up or down.
def neighbours(lock):
    out = []
    for i in range(4):
        d = int(lock[i])
        for nd in ((d + 1) % 10, (d - 1) % 10):
            out.append(lock[:i] + str(nd) + lock[i + 1:])
    return out

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int openLock(vector<string> &deadends, string target) {
        unordered_set<string> seen(deadends.begin(), deadends.end());
        if (seen.count("0000"))
            return -1;
        deque<string> queue = {"0000"};
        seen.insert("0000");
        for (int turns = 0; !queue.empty(); turns++) {
            for (int size = int(queue.size()); size > 0; size--) {
                string lock = queue.front();
                queue.pop_front();
                if (lock == target)
                    return turns;
                for (string &next : neighbours(lock)) {
                    if (seen.insert(next).second)
                        queue.push_back(next);
                }
            }
        }
        return -1;
    }

  private:
    // The 8 combinations one click away: each wheel turned up or down.
    vector<string> neighbours(const string &lock) {
        vector<string> out;
        string c = lock;
        for (int i = 0; i < 4; i++) {
            char original = c[i];
            c[i] = original == '9' ? '0' : char(original + 1);
            out.push_back(c);
            c[i] = original == '0' ? '9' : char(original - 1);
            out.push_back(c);
            c[i] = original;
        }
        return out;
    }
};

More Graph Traversal problems