Cracking the Safe in C++

C++Server Side ProgrammingProgramming

Suppose we have a box that is protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, ..., k-1. So, when we are putting a password, the last n digits entered will automatically be matched against the correct password.

So for example, assuming the correct password is "563", if we put "285639", the box will open because the correct password matches the suffix of the entered password. We have to find any password of minimum length that is guaranteed to open the box at some point of entering it.

When input is like n = 2 and k = 2, then the result can be “01100”, “00110”, “10011”, “11001”, any one of them.

To solve this, we will follow these steps −

• Define one set called visited
• Define a function dfs(), this will take s, k,
• for initialize i := 0, when i < k, update (increase i by 1), do −
• temp := s concatenate i as string
• if temp is not in visited, then −
• insert temp into visited
• temp := get substring of temp from index 1 to end
• dfs(temp, k)
• ret := ret concatenate i as string
• From the main method, do the following −
• if n is same as 1 and k is same as 1, then −
• return "0"
• ret := empty string, s := empty string
• for initialize i := 0, when i < n - 1, update (increase i by 1), do −
• s := s concatenate "0"
• dfs(s, k)
• for initialize i := 0, when i < n - 1, update (increase i by 1), do −
• ret := ret concatenate "0"
• return ret

Let us see the following implementation to get better understanding −

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
set <string> visited;
string ret;
string crackSafe(int n, int k) {
if(n == 1 && k == 1) return "0";
ret = "";
string s = "";
for(int i = 0; i < n - 1; i++){
s += "0";
}
dfs(s, k);
for(int i = 0; i < n - 1; i++) ret += "0";
return ret;
}
void dfs(string s, int k) {
string temp;
for(int i = 0; i < k; i++){
temp = s + to_string(i);
if(!visited.count(temp)){
visited.insert(temp);
temp = temp.substr(1);
dfs(temp, k);
ret += to_string(i);
}
}
}
};
main(){
Solution ob;
cout << (ob.crackSafe(2,2));
}

Input

2
2

Output

01100
Published on 02-Jun-2020 10:46:51