1 条题解
-
0
跳蚱蜢(Jumping Grasshoppers) 题解
思路分析
按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。
参考代码
#include <iostream> #include <string> #include <queue> #include <unordered_map> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string start = "012345678"; string target = "087654321"; unordered_map<string, int> dist; queue<string> q; dist[start] = 0; q.push(start); int d[4] = {-2, -1, 1, 2}; while (!q.empty()) { string u = q.front(); q.pop(); int step = dist[u]; if (u == target) { cout << step << "\n"; return 0; } int pos = 0; while (pos < 9 && u[pos] != '0') ++pos; for (int k = 0; k < 4; ++k) { int npos = (pos + d[k] + 9) % 9; string v = u; swap(v[pos], v[npos]); if (dist.find(v) == dist.end()) { dist[v] = step + 1; q.push(v); } } } return 0; }
- 1
信息
- ID
- 8807
- 时间
- 3000ms
- 内存
- 256MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者