赞
踩
- #include<iostream>
- #include<cstring>
- #include<algorithm>
- #include<queue>
- #include<unordered_map>
- using namespace std;
- int dx[4] = { 1,-1,0,0 };
- int dy[4] = { 0,0,-1,1 };
- int bfs(string state)
- {
- queue<string>q;
- unordered_map<string, int>d;
- q.push(state);
- d[state] = 0;
- while (q.size())
- {
- auto t = q.front();
-
- int dis = d[t];
- int k = t.find('x');
- int x = k / 3, y = k % 3;
-
- q.pop();
- string end = "12345678x";
- if (t == end)return d[t];
- for (int i = 0; i < 4; i++)
- {
- int a = x + dx[i], b = y + dy[i];
- if (a >= 0 && a < 3 && b >= 0 && b < 3)
- {
- swap(t[a * 3 + b], t[k]);
- if (!d.count(t))
- {
- d[t] = dis + 1;
- q.push(t);
- }
- swap(t[a * 3 + b], t[k]);
- }
-
- }
- }
-
- return -1;
- }
-
- int main()
- {
- string state;
- for (int i = 0; i < 9; i++)
- {
- char s;
- cin >> s;
- state += s;
- }
- cout << bfs(state);
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。