9.17算法

字串变换

?怎么转换?

?怎么识别?

//开两个数组记录串的转换关系,然后以原串为起点开始搜索,目标是b串
//尝试在第i位用第j种手段改变
//首先判断是否可行,然后再拼接
//用map记录这个串之前有没有被拼成过,如果被拼成过就直接退出
struct node {
	string str;
	int step;
};
const int maxn = 15;
string a, b;
string orginal[maxn], translated[maxn];
int n=0, ans;
unordered_mapma;
string trans(const string& str, int i, int j) {
	string ans = "";
	if (i + orginal[j].length() > str.length()) {//如果在
		return ans;//首先要保证的一点是后面有转化的子串,那么要保证的就是后面的长度够装得下这个子串
	}//如果转不下就return
	for (int k = 0; k < orginal[j].length(); k++) {//然后开始往后看,后面是不是第j种转换方式的前子串
		if (str[i + k] != orginal[j][k]) {
			return ans;
		}
		//上面是检测,至此就说明可以拼接
		ans = str.substr(0, i);//先获得前i位
		ans += translated[j];//把可以转换的转换掉
		ans += str.substr(i + orginal[j].length());//再加上后面的没有转换的部分
	}//o数组记录那些转换前的子串,t数组记录那些转换后的子串
	return ans;
}
void bfs() {
	queueq;
	node s;
	s.str = a;
	s.step = 0;
	q.push(s);
	while (!q.empty()) {
		node u = q.front();
		q.pop();
		string temp;
		if (ma.count(u.str) == 1) { continue; }
		if (u.str == b) { ans = u.step; break; }
		ma[u.str] = 1;
		for (int i = 0; i < u.str.length(); i++) {
			for (int j = 0; j < n; j++) {
				temp = trans(u.str, i, j);
				if (temp != "") {
					node v;
					v.str = temp;
					v.step = u.step + 1;
					q.push(v);
				}
			}
		}
	}
	if (ans > 10 || ans == 0)
		cout << "NO ANSWER!" << endl;
	else
		cout << ans << endl;

}//由当前串,从第一位向后遍历,并尝试第j种方式,如果
cin >> a >> b;
while (cin >> orginal[n] >> translated[n]) { n++; }
bfs();

你可能感兴趣的:(c++)