bfs:
经典 二重for循环:
1格子(字符串)8方向(选择)
while(!q.empty())
queue遍历
priority_queue优先级
void bfs() {
int ans = 0;
node u, v; u.str = s, u.step = 0;
q.push(u);
while (!q.empty()) {
u = q.front(); q.pop();
if (maps.count(u.str)) continue;
if (u.str == x) {
ans = u.step; break;
}
maps[u.str] = 1;//map!判重
for (int i = 0; i < u.str.length(); i++) {
for (int j = 0; j < n; j++) {
v.str = trans(u.str, i, j);
if (v.str != " ") {
v.step = u.step + 1; q.push(v);
}
}
}
}
if (ans == 0 || ans > 10) cout << "NO ANSWER!";
else cout << ans;
}
有序
(1) pair<int, int> p**;**
p.first & p.second
q.push(make_pair(u, v))
queue<node>
无序
(2) struct node() {
int a, b;
} n[10];
n.a & n.b
q.push(n)
map<key, value> maps;
if (m.count(n.b) == 1) //判重!!!
m[n.b] = 1
pass-by-reference 引用传递
function (const string &str)
&str 形参取址实参
const 常变量(保证引用,不作值的修改)
题目
code
#include<iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
map<string, int> maps;
struct node {
string str; int step;
};
queue<node> q;
string s, x, a[15], b[15];
int n = 0;
string trans(const string &str, int i, int num) {
if (i + a[num].length() > str.length()) return " ";
for (int j = 0; j < a[num].length(); j++)
if (str[i + j] != a[num][j]) return " ";
string nxt = str.substr(0, i);
nxt += b[num];
nxt += str.substr(i + a[num].length());//a:original
return nxt;
}
void bfs() {
int ans = 0;
node u, v; u.str = s, u.step = 0;
q.push(u);
while (!q.empty()) {
u = q.front(); q.pop();
if (maps.count(u.str)) continue;
if (u.str == x) {
ans = u.step; break;
}
maps[u.str] = 1;
for (int i = 0; i < u.str.length(); i++) {
for (int j = 0; j < n; j++) {
v.str = trans(u.str, i, j);
if (v.str != " ") {
v.step = u.step + 1; q.push(v);
}
}
}
}
if (ans == 0 || ans > 10) cout << "NO ANSWER!";
else cout << ans;
}
int main() {
cin >> s >> x;
while(cin >> a[n] >> b[n]) n++;
bfs();
return 0;
}