Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<vector>
- #include<queue>
- #include<string>
- #include <set>
- using namespace std;
- pair<int,string> minway(vector<int>g)
- {
- set<int>w;
- int a = 1, str = 0;
- for (int i = 0; i < 9; i++)
- {
- str += g[i] * a;
- a *= 10;
- }
- w.insert(str);
- queue<vector<int>>q;
- queue<int>numofswap;
- queue<string>way;
- q.push(g);
- numofswap.push(0);
- way.push("");
- while (!q.empty())
- {
- g = q.front();
- q.pop();
- int swapnum = numofswap.front();
- numofswap.pop();
- string way1 = way.front();
- way.pop();
- int zeroplace = 0;
- int t = 0;
- for (int i = 0; i < 9; ++i)
- {
- if ((g[i] == i + 1) || (i == 8 && g[i] == 0))
- ++t;
- if (g[i] == 0)
- zeroplace = i;
- }
- if (t == 9)
- {
- pair<int, string> m = make_pair( swapnum,way1 );
- return m;
- }
- else {
- if ((zeroplace != 0) && (zeroplace != 3) && (zeroplace != 6))
- {
- vector<int>h1 = g;
- swap(h1[zeroplace], h1[zeroplace - 1]);
- str = 0;
- a = 1;
- for (int i = 0; i < 9; i++)
- {
- str += h1[i] * a;
- a *= 10;
- }
- if (w.find(str) == w.end())
- {
- w.insert(str);
- q.push(h1);
- way.push(way1 + 'L');
- numofswap.push(swapnum + 1);
- }
- }
- if ((zeroplace != 2) && (zeroplace != 5) && (zeroplace != 8))
- {
- vector<int> h2 = g;
- swap(h2[zeroplace], h2[zeroplace + 1]);
- str = 0;
- a = 1;
- for (int i = 0; i < 9; i++)
- {
- str += h2[i] * a;
- a *= 10;
- }
- if (w.find(str) == w.end())
- {
- w.insert(str);
- q.push(h2);
- way.push(way1 + 'R');
- numofswap.push(swapnum + 1);
- }
- }
- if (zeroplace > 2)
- {
- vector<int>h3 = g;
- str = 0;
- a = 1;
- swap(h3[zeroplace], h3[zeroplace - 3]);
- for (int i = 0; i < 9; i++)
- {
- str += h3[i] * a;
- a *= 10;
- }
- if (w.find(str) == w.end())
- {
- w.insert(str);
- q.push(h3);
- way.push(way1 + 'U');
- numofswap.push(swapnum + 1);
- }
- }
- if (zeroplace < 6)
- {
- vector<int>h4 = g;
- swap(h4[zeroplace], h4[zeroplace + 3]);
- str = 0;
- a = 1;
- for (int i = 0; i < 9; i++)
- {
- str += h4[i] * a;
- a *= 10;
- }
- if (w.find(str) == w.end())
- {
- w.insert(str);
- q.push(h4);
- way.push(way1 + 'D');
- numofswap.push(swapnum + 1);
- }
- }
- }
- }
- pair<int, string>m = make_pair(-1, "");
- return m;
- }
- int main()
- {
- vector<int>g(9);
- for (int i = 0; i < 9; ++i)
- {
- cin >> g[i];
- }
- pair<int,string> m =minway(g);
- cout << m.first << endl << m.second << endl;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement