瞎扯
不知道这道题为什么可以评成蓝题,普通的 BFS 就过了。。
可以写双向 BFS。
题目
思路
暴力 BFS。
Code
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
#include <map>
#include <queue>
typedef std::pair<std::string, int> psi;
std::queue<psi> q;
std::map<std::string, bool> m;
int g[16][5], c[17];
std::string s, t;
std::string sss;
void bfs() {
while (!q.empty()) {
psi u = q.front();
q.pop();
if (u.first == t) {
std::cout << u.second << '
';
return;
}
for (int i = 0; i < 16; ++i) {
if (u.first[i] == '1') {
for (int j = 1; j <= c[i]; ++j) {
if (u.first[g[i][j]] == '0') {
std::string temp = "";
for (int k = 0; k < 16; ++k) {
if (k == i) temp += '0';
else if (k == g[i][j]) temp += '1';
else temp += u.first[k];
}
if (!m[temp]) {
m[temp] = true;
q.push(std::make_pair(temp, u.second + 1));
}
}
}
}
}
}
}
int main() {
for (int i = 1; i <= 4; ++i) {
std::cin >> sss;
s += sss;
}
for (int i = 1; i <= 4; ++i) {
std::cin >> sss;
t += sss;
}
c[0] = 2, g[0][1] = 1, g[0][2] = 4;
c[1] = 3, g[1][1] = 0, g[1][2] = 2, g[1][3] = 5;
c[2] = 3, g[2][1] = 1, g[2][2] = 3, g[2][3] = 6;
c[3] = 2, g[3][1] = 2, g[3][2] = 7;
c[4] = 3, g[4][1] = 0, g[4][2] = 5, g[4][3] = 8;
c[5] = 4, g[5][1] = 4, g[5][2] = 1, g[5][3] = 6, g[5][4] = 9;
c[6] = 4, g[6][1] = 5, g[6][2] = 7, g[6][3] = 2, g[6][4] = 10;
c[7] = 3, g[7][1] = 6, g[7][2] = 3, g[7][3] = 11;
c[8] = 3, g[8][1] = 9, g[8][2] = 4, g[8][3] = 12;
c[9] = 4, g[9][1] = 8, g[9][2] = 10, g[9][3] = 5, g[9][4] = 13;
c[10] = 4, g[10][1] = 9, g[10][2] = 11, g[10][3] = 6, g[10][4] = 14;
c[11] = 3, g[11][1] = 10, g[11][2] = 7, g[11][3] = 15;
c[12] = 2, g[12][1] = 13, g[12][2] = 8;
c[13] = 3, g[13][1] = 12, g[13][2] = 14, g[13][3] = 9;
c[14] = 3, g[14][1] = 13, g[14][2] = 15, g[14][3] = 10;
c[15] = 2, g[15][1] = 14, g[15][2] = 11;
q.push(std::make_pair(s, 0));
m[s] = true, bfs();
return 0;
}