Simple C++ implementation:
using namespace std;
vector<string> getNeighbours(string combo) {
vector<string> neighbours;
for(int i = 0; i < combo.size(); i++) {
int ival = (combo[i] - '0');
string next = combo.substr(0, i) + to_string((ival + 1 + 10) % 10) + combo.substr(i+1);
string prev = combo.substr(0, i) + to_string((ival - 1 + 10) % 10) + combo.substr(i+1);
neighbours.push_back(next);
neighbours.push_back(prev);
}
return neighbours;
}
int num_steps(std::string target_combo, std::vector<std::string> trapped_combos) {
// WRITE YOUR BRILLIANT CODE HERE
unordered_map<string, bool> visited;
unordered_map<string, bool> trapMap;
for(auto trap: trapped_combos) {
trapMap[trap] = true;
}
queue<string> q;
q.push("0000");
visited["0000"] = true;
int count = 0;
while(!q.empty()) {
int n = q.size();
for(int i = 0; i < n; i++) {
string newCombo = q.front();
q.pop();
if(newCombo == target_combo) return count;
vector<string> neighbours = getNeighbours(newCombo);
for(auto next: neighbours) {
if(!visited[next] && !trapMap[next]) {
q.push(next);
visited[next] = true;
}
}
}
count++;
}
return -1;
}