Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // BFS и алгоритм Дейкстры. Теория. Задача E.
- #include <bits/stdc++.h>
- using namespace std;
- set < string > used;
- map < string, string > from;
- string s, f;
- string up(string s) {
- if (s[0] != '9') {
- s[0] = s[0] + 1;
- }
- return s;
- }
- string down(string s) {
- if (s[3] != '1') {
- s[3] = s[3] - 1;
- }
- return s;
- }
- string shift_right(string s) {
- string n = "";
- n = n + s[3];
- n = n + s[0];
- n = n + s[1];
- n = n + s[2];
- return n;
- }
- string shift_left(string s) {
- string n = "";
- n = n + s[1];
- n = n + s[2];
- n = n + s[3];
- n = n + s[0];
- return n;
- }
- void bfs() {
- queue < string > q;
- q.push(s);
- used.insert(s);
- while (!q.empty()) {
- string c = q.front();
- q.pop();
- string u = up(c);
- string d = down(c);
- string r = shift_right(c);
- string l = shift_left(c);
- if (used.find(u) == used.end()) {
- from[u] = c;
- q.push(u);
- used.insert(u);
- }
- if (used.find(d) == used.end()) {
- from[d] = c;
- q.push(d);
- used.insert(d);
- }
- if (used.find(r) == used.end()) {
- from[r] = c;
- q.push(r);
- used.insert(r);
- }
- if (used.find(l) == used.end()) {
- from[l] = c;
- q.push(l);
- used.insert(l);
- }
- }
- }
- void print_way() {
- string v = f;
- from[s] = "0000";
- vector < string > way;
- while (from[v] != "0000") {
- way.push_back(v);
- v = from[v];
- }
- way.push_back(s);
- reverse(way.begin(), way.end());
- for (auto e : way) cout << e << endl;
- }
- int main() {
- cin >> s >> f;
- bfs();
- print_way();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement