Skip to main content

Breadth First Search

Open the Lock

Problem Statement

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

Example 1

Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
Explanation: 
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102".

Example 2

Input: deadends = ["8888"], target = "0009"
Output: 1
Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".

Try here before watching the video.

Video Explanation

Java Code

import java.util.*;

class Solution {
    public int openLock(String[] deadends, String target) {
        Set<String> seen = new HashSet<>();

        Map<Character, List<Character>> turnMap = new HashMap<>() {
            {
                put('0', List.of('1', '9'));
                put('1', List.of('2', '0'));
                put('2', List.of('3', '1'));
                put('3', List.of('4', '2'));
                put('4', List.of('5', '3'));
                put('5', List.of('6', '4'));
                put('6', List.of('7', '5'));
                put('7', List.of('8', '6'));
                put('8', List.of('9', '7'));
                put('9', List.of('0', '8'));
            }
        };

        for(String deadend : deadends) {
            seen.add(deadend);
        }

        if(seen.contains("0000")) {
            return -1;
        }

        Queue<String> queue = new LinkedList<>();
        queue.add("0000");
        seen.add("0000");

        int turns = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                String currState = queue.poll();
                if(currState.equals(target)) {
                    return turns;
                }
                
                char[] currStateArr = currState.toCharArray();
                for(int j = 0; j < currStateArr.length; j++) {
                    char currNumber = currStateArr[j];
                    for(char ch : turnMap.get(currNumber)) {
                        currStateArr[j] = ch;
                        String newState = new String(currStateArr);
                        if(!seen.contains(newState)) {
                            queue.add(newState);
                            seen.add(newState);
                        }
                        currStateArr[j] = currNumber;
                    }
                }
            }
            turns += 1;
        }
        return -1;
    }
}

C++ Code

#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());

        unordered_map<char, vector<char>> turnMap = {
            {'0', {'1', '9'}},
            {'1', {'2', '0'}},
            {'2', {'3', '1'}},
            {'3', {'4', '2'}},
            {'4', {'5', '3'}},
            {'5', {'6', '4'}},
            {'6', {'7', '5'}},
            {'7', {'8', '6'}},
            {'8', {'9', '7'}},
            {'9', {'0', '8'}}
        };

        if (seen.count("0000")) {
            return -1;
        }

        queue<string> q;
        q.push("0000");
        seen.insert("0000");

        int turns = 0;
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                string currState = q.front();
                q.pop();

                if (currState == target) {
                    return turns;
                }

                for (int j = 0; j < currState.size(); ++j) {
                    char currNumber = currState[j];
                    for (char ch : turnMap[currNumber]) {
                        currState[j] = ch;
                        string newState = currState;
                        if (seen.find(newState) == seen.end()) {
                            q.push(newState);
                            seen.insert(newState);
                        }
                        currState[j] = currNumber;
                    }
                }
            }
            turns += 1;
        }
        return -1;
    }
};

Python Code

from typing import List
from collections import deque

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

        turn_map = {
            '0': ['1', '9'],
            '1': ['2', '0'],
            '2': ['3', '1'],
            '3': ['4', '2'],
            '4': ['5', '3'],
            '5': ['6', '4'],
            '6': ['7', '5'],
            '7': ['8', '6'],
            '8': ['9', '7'],
            '9': ['0', '8']
        }

        if "0000" in seen:
            return -1

        queue = deque(["0000"])
        seen.add("0000")

        turns = 0
        while queue:
            size = len(queue)
            for _ in range(size):
                curr_state = queue.popleft()

                if curr_state == target:
                    return turns

                for j in range(len(curr_state)):
                    curr_number = curr_state[j]
                    for ch in turn_map[curr_number]:
                        new_state = curr_state[:j] + ch + curr_state[j+1:]
                        if new_state not in seen:
                            queue.append(new_state)
                            seen.add(new_state)

            turns += 1
            
        return -1

Javascript Code

var openLock = function(deadends, target) {
    let seen = new Set();

    const turnMap = {
        '0': ['1', '9'],
        '1': ['2', '0'],
        '2': ['3', '1'],
        '3': ['4', '2'],
        '4': ['5', '3'],
        '5': ['6', '4'],
        '6': ['7', '5'],
        '7': ['8', '6'],
        '8': ['9', '7'],
        '9': ['0', '8']
    };

    for (const deadend of deadends) {
        seen.add(deadend);
    }

    if (seen.has("0000")) {
        return -1;
    }

    let queue = ["0000"];
    seen.add("0000");

    let turns = 0;
    while (queue.length > 0) {
        const size = queue.length;
        for (let i = 0; i < size; i++) {
            const currState = queue.shift();
            if (currState === target) {
                return turns;
            }

            const currStateArr = currState.split('');
            for (let j = 0; j < currStateArr.length; j++) {
                const currNumber = currStateArr[j];
                for (const ch of turnMap[currNumber]) {
                    currStateArr[j] = ch;
                    const newState = currStateArr.join('');
                    if (!seen.has(newState)) {
                        queue.push(newState);
                        seen.add(newState);
                    }
                    currStateArr[j] = currNumber;
                }
            }
        }
        turns += 1;
    }
    return -1;
};

Go Code

func openLock(deadends []string, target string) int {
	seen := make(map[string]bool)

	turnMap := map[byte][]byte{
		'0': {'1', '9'},
		'1': {'2', '0'},
		'2': {'3', '1'},
		'3': {'4', '2'},
		'4': {'5', '3'},
		'5': {'6', '4'},
		'6': {'7', '5'},
		'7': {'8', '6'},
		'8': {'9', '7'},
		'9': {'0', '8'},
	}

	for _, deadend := range deadends {
		seen[deadend] = true
	}

	if seen["0000"] {
		return -1
	}

	queue := []string{"0000"}
	seen["0000"] = true

	turns := 0
	for len(queue) > 0 {
		size := len(queue)
		for i := 0; i < size; i++ {
			currState := queue[0]
			queue = queue[1:]

			if currState == target {
				return turns
			}

			currStateArr := []byte(currState)
			for j := 0; j < len(currStateArr); j++ {
				currNumber := currStateArr[j]
				for _, ch := range turnMap[currNumber] {
					currStateArr[j] = ch
					newState := string(currStateArr)
					if !seen[newState] {
						queue = append(queue, newState)
						seen[newState] = true
					}
					currStateArr[j] = currNumber
				}
			}
		}
		turns++
	}
	return -1
}

Complexity Analysis

  • Time Complexity: O(N2 ∗ AN + D) where A is the number of digits in our alphabet, N is the number of digits in the lock, and D is the size of deadends. We might visit every lock combination, plus we need to instantiate our set seen. When we visit every lock combination, we spend O(N2) time enumerating through and constructing each node.
  • Space Complexity: O(AN + D), for the queue and the set seen.