题意:
就是华容道的玩法问你A和B交换位置最少需要的次数。其他位置不用管,最开始没有注意到这个细节只过了两个点。
思路:
就是BFS来贪心,我们把与空格相邻的位置都与空格进行交换,压入队列,把最终态一定要设置好,就可以做了,我是用把二维矩阵转换成字符串的方法来写的,相当于模拟的是每个状态,代码有点长还有点丑。
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(0)
#define int long long
#define endl "\n"
#define xx first
#define yy second
using namespace std;
typedef pair<int, int> PII;
const int N = 5;
int n, m, k, _, cot;
char g[N][N], t1[N][N];
int dist[N*100];
map<string, int> mp;
int ans;
bool st[N*10000];
void copyy()
{
for(int i = 1; i <= 2; i ++)
{
for(int j = 1; j <= 3; j ++)
{
t1[i][j] = g[i][j];
}
}
}
string convert()
{
string tmp = "";
for(int i = 1; i <= 2; i ++)
{
for(int j = 1; j <= 3; j ++)
{
tmp += t1[i][j];
}
}
return tmp;
}
void swapp(int a1, int b1, int a2, int b2)
{
char x = t1[a2][b2];
t1[a2][b2] = t1[a1][b1];
t1[a1][b1] = x;
}
void bfs()
{
string tmp = "";
for(int i = 1; i <= 2; i ++)
{
for(int j = 1; j <= 3; j ++)
{
tmp += g[i][j];
t1[i][j] = g[i][j];
}
}
int aa1 = 0, bb1 = 0, aa2 = 0, bb2 = 0;
int a1 = 0, b1 = 0, a2 = 0, b2 = 0;
for(int i = 1; i <= 2; i ++)
{
for(int j = 1; j <= 3; j ++)
{
if(g[i][j] == 'A') aa1 = i, bb1 = j;
if(g[i][j] == 'B') aa2 = i, bb2 = j;
}
}
queue<string> q;
q.push(tmp);
mp[tmp] = ++cot;
st[cot] = 1;
while(!q.empty())
{
string t = q.front();
q.pop();
for(int i = 0; i < 3; i ++) g[1][i+1] = t[i];
for(int i = 3; i < 6; i ++) g[2][i-2] = t[i];
for(int i = 1; i <= 2; i ++)
{
for(int j = 1; j <= 3; j ++)
{
if(g[i][j] == ' ')
{
a1 = i, b1 = j;
if(i+1 == 2)
{
a2 = i+1, b2 = j;
copyy();
swapp(a1, b1, a2, b2);
string t2 = convert();
if(mp[t2] == 0)
{
mp[t2] = ++cot;
}
if(!st[mp[t2]])
{
dist[mp[t2]] = dist[mp[t]]+1;
st[mp[t2]] = 1;
if(t1[aa1][bb1] == 'B' && t1[aa2][bb2] == 'A')
{
ans = dist[mp[t]]+1;
return;
}
q.push(t2);
}
}
if(i-1 == 1)
{
a2 = i-1, b2 = j;
copyy();
swapp(a1, b1, a2, b2);
string t2 = convert();
if(mp[t2] == 0)
{
mp[t2] = ++cot;
}
if(!st[mp[t2]])
{
dist[mp[t2]] = dist[mp[t]]+1;
st[mp[t2]] = 1;
if(t1[aa1][bb1] == 'B' && t1[aa2][bb2] == 'A')
{
ans = dist[mp[t]]+1;
return;
}
q.push(t2);
}
}
if(j+1 <= 3)
{
a2 = i, b2 = j+1;
copyy();
swapp(a1, b1, a2, b2);
string t2 = convert();
if(mp[t2] == 0)
{
mp[t2] = ++cot;
}
if(!st[mp[t2]])
{
dist[mp[t2]] = dist[mp[t]]+1;
st[mp[t2]] = 1;
if(t1[aa1][bb1] == 'B' && t1[aa2][bb2] == 'A')
{
ans = dist[mp[t]]+1;
return;
}
q.push(t2);
}
}
if(j-1 >= 1)
{
a2 = i, b2 = j-1;
copyy();
swapp(a1, b1, a2, b2);
string t2 = convert();
if(mp[t2] == 0)
{
mp[t2] = ++cot;
}
if(!st[mp[t2]])
{
dist[mp[t2]] = dist[mp[t]]+1;
st[mp[t2]] = 1;
if(t1[aa1][bb1] == 'B' && t1[aa2][bb2] == 'A')
{
ans = dist[mp[t]]+1;
return;
}
q.push(t2);
}
}
break;
}
}
}
}
}
signed main()
{
IOS;
string s1, s2;
getline(cin, s1);
getline(cin, s2);
for(int i = 0; i < 3; i ++) g[1][i+1] = s1[i];
for(int i = 0; i < 3; i ++) g[2][i+1] = s2[i];
bfs();
cout << ans << endl;
return 0;
}