854. K-Similar Strings
Input: A = "ab", B = "ba"
Output: 1Input: A = "abc", B = "bca"
Output: 2Input: A = "abac", B = "baca"
Output: 2Input: A = "aabc", B = "abca"
Output: 2// BFS
int kSimilarity(string A, string B) {
if (A == B) return 0;
int res = 0, len = A.length();
queue<string> q({A});
unordered_set<string> visited({A});
while (!q.empty()) {
++res;
for (int k = q.size() - 1; k >= 0; --k) {
string str = q.front(); q.pop();
int i = 0;
while (str[i] == B[i]) ++i;
for (int j = i + 1; j < len; ++j) {
if (str[j] == B[j] || str[i] != B[j]) continue; // Skip already sorted or unmatched
swap(str[i], str[j]);
if (str == B) return res;
if (!visited.count(str)) {
q.push(str);
visited.insert(str);
}
swap(str[i], str[j]); // reset
}
}
}
return res;
}Last updated