在一个 4×4的方框内摆放了若干个相同的玩具,某人想将这些玩具重新摆放成为他心中理想的状态,规定移动时只能将玩具向上下左右四个方向移动,并且移动的位置不能有玩具,请你用最少的移动次数将初始的玩具状态移动到目标状态。
输入格式
前四行表示玩具的初始状态,每行 4个数字 1 或 0,1 表示方格中放置了玩具,0表示没有放置玩具。接着是一个空行。接下来四行表示玩具的目标状态,每行 4个数字 1 或 0,意义同上。
输出格式
输出一个整数,表示所需要的最少移动次数。
输入样例:
1111 0000 1110 0010 1010 0101 1010 0101
输出样例:
4
晦涩难懂的位运算,还只得了个PAC,不是很推荐的算法
#include#include using namespace std; const int N = 4; int start, goal; int dist[1 << N * N], visited[1 << N * N]; int bfs() { queue 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; int start, goal; 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; }
等我写个好算法:
#include#include #include #include using namespace std; const int maxm = 100005; int a, b, dis[1 << 16 + 1] = { 0 }, now, ne; char str[5]; queue q; void change(int x); int main() { int n, i, j, k, sum; a = 0; b = 0; for (i = 1; i <= 4; i++) { scanf("%s", str); for (j = 0; str[j] != ' '; j++) b = b * 2 + str[j] - '0'; } for (i = 1; i <= 4; i++) { scanf("%s", str); for (j = 0; str[j] != ' '; j++) a = a * 2 + str[j] - '0'; } dis[a] = 1; q.push(a); while (!q.empty()) { now = q.front(); q.pop(); for (i = 0; i < 16; i++) { if (now&(1 << i)) { ne = (1 << i) ^ now; if (i % 4 > 0) change(i - 1); if (i % 4 < 3) change(i + 1); if (i / 4 > 0) change(i - 4); if (i / 4 < 3) change(i + 4); } if (dis[b]) { printf("%dn", dis[b] - 1); return 0; } } } } void change(int x) { if (ne & (1 << x)) return; int xx = ne + (1 << x); if (dis[xx]) return; dis[xx] = dis[now] + 1; q.push(xx); }
AC了,真美妙。
ps:缩进什么没搞好的,可以用devc++重新设置一下子



