思路:
- 二进制表示当前状态
- 当相邻的数不同时(即、一个为0一个为1),交换一下
- 当出队时找到 start 直接返回 dist
核心代码一: (占一行)
int tt = t ^ (1 << last) ^ (1 << now);
作用:交换二进制表示的两位数
- 我们可知,当两位数不同时我们才交换,如此我们只需令
当前数 ^ (1 << x)
,如此将当前数的x
位上的数字变为我们想要的数字
核心代码二:(占四行)
if(i % 4 > 0 ) change(t, i, i - 1); // 和左边交换
if(i % 4 < 3 ) change(t, i, i + 1); // 和右边交换
if(i / 4 > 0 ) change(t, i, i - 4); // 和上边交换
if(i / 4 < 3 ) change(t, i, i + 4); // 和下边交换
将 4x4 的矩阵映射为 0~15 的 16 位二进制数
并实施 change 交换相邻两位数字
总体代码如下:
#include <bits/stdc++.h>
#define fast ios::sync_with_stdio(false), cin.tie(nullptr); cout.tie(nullptr)
#define x first
#define y second
#define int long long
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e6 + 10, M = 1010;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int n, m;
int start, ed;
string str[10];
int dist[N];
bool st[N];
queue<int> q;
// 调试代码,
// 作用:输出矩阵
// void print(int x)
// {
// for (int i = 0, t = 15; i < 4; i ++ )
// {
// for (int j = 0; j < 4; j ++, t -- )
// cout << ( (x >> t) & 1) << " ";
// cout << endl;
// }
// cout << endl;
// }
// 交换 last 与 now 位上的数字
void change(int t, int last, int now)
{
if( ((t >> last) & 1) == ((t >> now) & 1))
return;
int tt = t ^ (1 << last) ^ (1 << now);
dist[tt] = dist[t] + 1;
q.push(tt);
}
// 宽搜框架
int bfs()
{
memset(dist, 0x3f, sizeof dist);
q.push(start);
dist[start] = 0;
int cnt = 0;
while(q.size())
{
int t = q.front();
q.pop();
if(t == ed) return dist[ed];
if(st[t]) continue;
st[t] = true;
// 直接搜即可(总状态位 2^16 = 65536 种,
// bfs 为线性时间复杂度,直接搜 时间很充足
for (int i = 15; i >= 0 ; i -- )
{
// if( ((t >> i) & 1) ^ ((start >> i) & 1))
// 本想简化一下代码,,但此行代码不可加上
// 加上会 WA 一个数据
// 数据如下:
// 0011
// 1100
// 0011
// 1100
// 1111
// 1001
// 1001
// 0000
// 若加上则左上角的11永远出不去,无法到外面导致返回无解 -1
// 因此最终代码代码为:
// if( ((t >> i) & 1) ^ ((start >> i) & 1))
//{
if(i % 4 > 0 ) change(t, i, i - 1); // 和左边交换
if(i % 4 < 3 ) change(t, i, i + 1); // 和右边交换
if(i / 4 > 0 ) change(t, i, i - 4); // 和上边交换
if(i / 4 < 3 ) change(t, i, i + 4); // 和下边交换
//}
}
cnt ++;
}
return -1;
}
void solve()
{
for (int i = 0; i < 4; i ++ )
cin >> str[i];
// 状压 ed
for (int i = 0, t = 0; i < 4; i ++ )
for (int j = 0; j < 4; j ++ , t ++ )
ed = (ed << 1) + (str[i][j] - '0');
for (int i = 0; i < 4; i ++ )
cin >> str[i];
// 状压 start
for (int i = 0, t = 0; i < 4; i ++ )
for (int j = 0; j < 4; j ++ , t ++ )
start = (start << 1) + (str[i][j] - '0');
cout << bfs() << endl;
return;
}
signed main()
{
//fast;
int T = 1;
//cin >> T;
while(T -- )
solve();
return 0;
}