1 条题解
-
0
#include <bits/stdc++.h> using namespace std; int n; int ten[10]; map<int, int> dis; queue<int> q; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n; ten[0] = 1; for (int i = 1; i <= 8; i++) ten[i] = ten[i - 1] * 10; q.push(n); dis[n] = 0; while (!q.empty() && dis.find(123804765) == dis.end()) { int now = q.front(); q.pop(); // 0 的位置、目标的位置 int pos = -1, t; for (int i = 0; i <= 8; i++) if (now / ten[i] % 10 == 0) { pos = i; break; } // 上下左右 for (int i = 1; i <= 4; i++) { if (i == 1) t = pos - 3; if (i == 2) t = pos + 3; if (i == 3) { if (pos % 3 == 0) t = -1; else t = pos - 1; } if (i == 4) { if (pos % 3 == 2) t = -1; else t = pos + 1; } if (0 <= t && t <= 8) { // pos 上是 0,t 上是 x int x = now / ten[t] % 10; int nxt = now - x * ten[t] + x * ten[pos]; if (dis.find(nxt) == dis.end()) { dis[nxt] = dis[now] + 1; q.push(nxt); } } } } cout << dis[123804765]; return 0; }
- 1
信息
- ID
- 1772
- 时间
- 1000ms
- 内存
- 125MiB
- 难度
- 4
- 标签
- 递交数
- 18
- 已通过
- 12
- 上传者