题目链接:https://ac.nowcoder.com/acm/contest/6357/B
Description
牛牛收到了一个任务,任务要求牛牛破译一个密码。牛牛将被给予两个字符串s1和s2,均由四个小写字母构成。需要破译的密码为从s1变换到s2最少需要的变换次数。
变换的方式是这样:每次变换可以选择当前字符串中的一个位置,然后剩下的三个位置的字符从左到右分别加上2,3,5,若是超出’z’,则重新从’a’开始,例如:对于字符串"abcd",我们选择’c’的位置进行变换,则变换之后的字符串为"ceci";对于字符串"qyzr",我们选择’r’位置进行变换,则变换之后的字符串为"sber"。
Sample Input
“aaaa”,“ccgk”
Sample Output
2
Interpretation
第一次变换选择第一个’a’,变成"acdf",第二次变换选择第二个’c’,变成"ccgk",故答案为2
Solution
BFS
定义一个map<string,int> m,用来记录到当前字符串最少需要的变换次数,m[s1]初始化为0,表示从s1变换到s1的变换次数为0;将s1压入队列,然后将变换后的三个字符串也压入队列,直到当前字符串为s2,搜索结束,返回m[s2],即从s1变换到s2最少需要的变换次数。
Code
class Solution {
public:
/**
* 返回最终的答案
* @param s1 string字符串 表示初始的字符串
* @param s2 string字符串 表示目标的字符串
* @return int整型
*/
int solve(string s1, string s2) {
queue<string> q;
map<string, int> m;
m[s1] = 0;
q.push(s1);
while (!q.empty()) {
string f = q.front();
if (f == s2) return m[s2];
q.pop();
for (int i = 0; i < 4; i++) {
string s = f;
int c = 2;
for (int j = 0; j < 4; j++) {
if (i == j) continue;
s[j] = (s[j] - 'a' + c) % 26 + 'a';
if (c == 2) c = 3;
else if (c == 3) c = 5;
}
if (!m[s]) {
m[s] = m[f] + 1;
q.push(s);
}
}
}
}
};