Advertisement
AlexGo11

Untitled

Jan 2nd, 2020
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. // BFS и алгоритм Дейкстры. Теория. Задача E.
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. set < string > used;
  5. map < string, string > from;
  6. string s, f;
  7.  
  8. string up(string s) {
  9.     if (s[0] != '9') {
  10.         s[0] = s[0] + 1;
  11.     }
  12.     return s;
  13. }
  14.  
  15. string down(string s) {
  16.     if (s[3] != '1') {
  17.         s[3] = s[3] - 1;
  18.     }
  19.     return s;
  20. }
  21.  
  22. string shift_right(string s) {
  23.     string n = "";
  24.     n = n + s[3];
  25.     n = n + s[0];
  26.     n = n + s[1];
  27.     n = n + s[2];
  28.     return n;
  29. }
  30.  
  31. string shift_left(string s) {
  32.     string n = "";
  33.     n = n + s[1];
  34.     n = n + s[2];
  35.     n = n + s[3];
  36.     n = n + s[0];
  37.     return n;
  38. }
  39.  
  40. void bfs() {
  41.     queue < string > q;
  42.     q.push(s);
  43.     used.insert(s);
  44.     while (!q.empty()) {
  45.         string c = q.front();
  46.         q.pop();
  47.        
  48.         string u = up(c);
  49.         string d = down(c);
  50.         string r = shift_right(c);
  51.         string l = shift_left(c);
  52.        
  53.         if (used.find(u) == used.end()) {
  54.             from[u] = c;
  55.             q.push(u);
  56.             used.insert(u);
  57.         }
  58.        
  59.         if (used.find(d) == used.end()) {
  60.             from[d] = c;
  61.             q.push(d);
  62.             used.insert(d);
  63.         }
  64.        
  65.         if (used.find(r) == used.end()) {
  66.             from[r] = c;
  67.             q.push(r);
  68.             used.insert(r);
  69.         }
  70.        
  71.         if (used.find(l) == used.end()) {
  72.             from[l] = c;
  73.             q.push(l);
  74.             used.insert(l);
  75.         }
  76.     }
  77. }
  78.  
  79. void print_way() {
  80.     string v = f;
  81.     from[s] = "0000";
  82.     vector < string > way;
  83.     while (from[v] != "0000") {
  84.         way.push_back(v);
  85.         v = from[v];
  86.     }
  87.     way.push_back(s);
  88.     reverse(way.begin(), way.end());
  89.     for (auto e : way) cout << e << endl;
  90. }
  91.  
  92. int main() {
  93.     cin >> s >> f;
  94.     bfs();
  95.     print_way();
  96.     return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement