AcWing 1103. 棋盘游戏
原题链接
简单
作者:
王小强
,
2021-02-02 18:03:30
,
所有人可见
,
阅读 307
想找抽风姐姐改进版的代码的看这里!
#include <iostream>
#include <queue>
using namespace std;
const int N = 4;
int start, goal;
int dist[1 << N * N], visited[1 << N * N];
int bfs() {
queue<int> q{{start}};
visited[start] = 1; // mark as visited
static constexpr int dirs[] { 0, -1, 0, 1, 0 };
while (not q.empty()) {
const int cur_state = q.front(); q.pop();
if (cur_state == goal) return dist[cur_state];
for (int i = 0; i < N * N; ++i) {
if (!(cur_state & (1 << i))) continue;
// 与四周的0交换 (一维坐标转二维坐标)
int x = i % N, y = i / N;
for (int d = 0; d < 4; ++d) { // 上左下右四个方向
int nx = x + dirs[d], ny = y + dirs[d + 1];
// out of the boundary or toy
if (nx < 0 || ny < 0 || nx == N || ny == N || cur_state & (1 << ny * N + nx))
continue;
// change current state to the new state!(swap)
int new_state = cur_state;
new_state ^= 1 << i; // flip (0变1)
new_state ^= 1 << ny * N + nx; // flip(1变0)
if (visited[new_state] ) continue;
visited[new_state] = 1;
q.emplace(new_state);
dist[new_state] = dist[cur_state] + 1; // 从旧状态变成新状态(多走了一步)
}
}
}
return -1;
}
int main(void) {
char c;
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x) {
cin >> c;
if (c == '1') start |= 1 << y * N + x;
}
for (int y = 0; y < N; ++y)
for (int x = 0; x < N; ++x) {
cin >> c;
if (c == '1') goal |= 1 << y * N + x;
}
cout << bfs() << endl;
}