// JavaScript implementation of the approach
// Function to return the minimum number of
// operations to convert string A to B
function minOperations(s, f) {
// If both the strings are equal then
// no operation needs to be performed
if (s === f) {
return 0;
}
let vis = {};
let n = s.length;
let pos = 0;
for (let i = 0; i < n; i++) {
if (s[i] === '_') {
// store the position of '_'
pos = i;
break;
}
}
// to store the generated string at every
// move and the position of '_' within it
let q = [];
q.push([s, pos]);
// vis will store the minimum operations
// to reach that particular string
vis[s] = 0;
while (q.length) {
let [ss, pp] = q[0];
// minimum moves to reach the string ss
let dist = vis[ss];
q.shift();
ss = ss.split('');
// try all 4 possible operations
// if '_' can be swapped with
// the character on it's left
if (pp > 0) {
// swap with the left character
[ss[pp], ss[pp - 1]] = [ss[pp - 1], ss[pp]];
ss = ss.join('');
// if the string is generated
// for the first time
if (!(ss in vis)) {
// if generated string is
// the required string
if (ss === f) {
return dist + 1;
}
// update the distance for the
// currently generated string
vis[ss] = dist + 1;
q.push([ss, pp - 1]);
}
ss = ss.split('');
// restore the string before it was
// swapped to check other cases
[ss[pp], ss[pp - 1]] = [ss[pp - 1], ss[pp]];
ss = ss.join('');
}
// swap '_' with the character
// on it's right this time
if (pp < n - 1) {
ss = ss.split('');
[ss[pp], ss[pp + 1]] = [ss[pp + 1], ss[pp]];
ss = ss.join('');
if (!(ss in vis)) {
if (ss === f) {
return dist + 1;
}
vis[ss] = dist + 1;
q.push([ss, pp + 1]);
}
ss = ss.split('');
[ss[pp], ss[pp + 1]] = [ss[pp + 1], ss[pp]];
ss = ss.join('');
}
// if '_' can be swapped
// with the character 'i+2'
if (pp > 1 && ss[pp - 1] !== ss[pp - 2]) {
ss = ss.split('');
[ss[pp], ss[pp - 2]] = [ss[pp - 2], ss[pp]];
ss = ss.join('');
if (!(ss in vis)) {
if (ss === f) {
return dist + 1;
}
vis[ss] = dist + 1;
q.push([ss, pp - 2]);
}
ss = ss.split('');
[ss[pp], ss[pp - 2]] = [ss[pp - 2], ss[pp]];
ss = ss.join('');
}
// if '_' can be swapped
// with the character at 'i+2'
if (pp < n - 2 && ss[pp + 1] !== ss[pp + 2]) {
ss = ss.split('');
[ss[pp], ss[pp + 2]] = [ss[pp + 2], ss[pp]];
ss = ss.join('');
if (!(ss in vis)) {
if (ss === f) {
return dist + 1;
}
vis[ss] = dist + 1;
q.push([ss, pp + 2]);
}
ss = ss.split('');
[ss[pp], ss[pp + 2]] = [ss[pp + 2], ss[pp]];
ss = ss.join('');
}
}
}
// Driver Code
let A = "aba_a";
let B = "_baaa";
console.log(minOperations(A, B))
// This code is contributed by codebraxnzt