Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <map>
- #include <algorithm>
- using namespace std;
- vector<vector<int>> neighbours(vector<int> curr){ // туда пускаем вершину, а получаем вектор из соседей
- int zp = 0;
- for (int i = 0; i < 9; i++)
- if (curr[i] == 0)
- zp = i;
- vector<vector<int>> ans;
- int zi = zp / 3;
- int zj = zp % 3;
- if (zi > 0){
- auto tmp = curr;
- swap(tmp[zp],tmp[zp-3]);
- ans.push_back(tmp);
- }
- if (zi < 2){
- auto tmp = curr;
- swap(tmp[zp],tmp[zp+3]);
- ans.push_back(tmp);
- }
- if (zj > 0){
- auto tmp = curr;
- swap(tmp[zp],tmp[zp-1]);
- ans.push_back(tmp);
- }
- if (zj < 2){
- auto tmp = curr;
- swap(tmp[zp],tmp[zp+1]);
- ans.push_back(tmp);
- }
- return ans;
- }
- bool solve( vector<int> v ){ // смотрим, можно ли решить
- int inv = 0;
- for (int i=0; i<9; ++i)
- if (v[i])
- for (int j=0; j<i; ++j)
- if (v[j] > v[i])
- ++inv;
- if (inv % 2 == 0)
- return true;
- else
- return false;
- }
- char direction( vector<int> s, vector<int> f){ // определяем как попасть из s в f
- int zp1 = 0, zp2 = 0;
- for (int i = 0; i < 9; i++){
- if (s[i] == 0)
- zp1 = i;
- if (f[i] == 0)
- zp2 = i;
- }
- int d = zp2 - zp1;
- if (d == 3)
- return 'D';
- if (d == -3)
- return 'U';
- if (d == 1)
- return 'R';
- if (d == -1)
- return 'L';
- return 0; // default value
- }
- void print_vec(vector<int> v){
- cout << v[0] << " " << v[1] << " " << v[2] << endl;
- cout << v[3] << " " << v[4] << " " << v[5] << endl;
- cout << v[6] << " " << v[7] << " " << v[8] << endl;
- cout << endl;
- }
- int main(){
- queue<vector<int>> q;
- vector<int> s(9);
- vector<int> f(9);
- for (int i = 0; i < 9; i++){
- cin >> s[i];
- f[i] = i+1;
- }
- f[8] = 0;
- if (!solve(s)){
- cout << -1 << endl;
- return 0;
- }
- q.push(s);
- map<vector<int>, int> d; // расстояние
- map<vector<int>, vector<int>> p; // предки
- d[s] = 0;
- auto curr = s;
- while (curr != f){
- curr = q.front();
- q.pop();
- auto nb = neighbours(curr);
- for (auto elem : nb)
- if (d.find(elem) == d.end()){
- d[elem] = d[curr] + 1;
- q.push(elem);
- p[elem] = curr;
- }
- }
- cout << d[f] << endl;
- string path;
- curr = f;
- while (curr != s){
- path.push_back(direction(p[curr], curr));
- curr = p[curr];
- }
- reverse(path.begin(), path.end());
- cout << path << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement