Advertisement
vovanhoangtuan

3A - Shortest path of the king

Nov 10th, 2020
1,099
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <cstdio>
  3.  
  4. using namespace std;
  5.  
  6. struct Point{
  7.     int x, y, indexPre;
  8.  
  9.     Point(int x1 = 0, int y1 = 0)
  10.     {
  11.         x = x1;
  12.         y = y1;
  13.     }
  14.  
  15.     bool operator!=(Point a)
  16.     {
  17.         return x != a.x || y != a.y;
  18.     }
  19.  
  20. };
  21.  
  22. string s, t;
  23. int moveAround[8][2] = {{-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}};
  24. string index[8] = {"LU", "U", "RU", "R", "RD", "D", "LD", "L"};
  25. Point start, finish;
  26.  
  27. Point toPoint(string a)
  28. {
  29.     int first = (a[0] - '0') - 48;
  30.     int second = (int)a[1] - 48;
  31.     return Point(first, second);
  32. }
  33.  
  34. void BFS(Point start)
  35. {
  36.     queue<Point> q;
  37.     vector<int> path;
  38.     bool visited[9][9];
  39.     int pre[9][9];
  40.     Point prePoint[9][9];
  41.  
  42.     memset(visited, 0, sizeof visited);
  43.  
  44.     pre[start.x][start.y] = -1;
  45.     prePoint[start.x][start.y] = start;
  46.  
  47.     q.push(start);
  48.     visited[start.x][start.y] = true;
  49.  
  50.     while(!q.empty())
  51.     {
  52.         Point next = q.front();
  53.         q.pop();
  54.         for (int i = 0; i < 8; i++)
  55.         {
  56.             int newX = next.x + moveAround[i][0];
  57.             int newY = next.y + moveAround[i][1];
  58.             if (newX >= 1 && newX <= 8 && newY >= 1 && newY <= 8 && visited[newX][newY] == false)
  59.             {
  60.                 visited[newX][newY] = true;
  61.                 Point temp = Point(newX, newY);
  62.  
  63.                 pre[newX][newY] = i;
  64.                 prePoint[newX][newY] = next;
  65.  
  66.                 q.push(temp);
  67.             }
  68.         }
  69.     }
  70.  
  71.     Point s = finish;
  72.     while (s != start)
  73.     {
  74.         path.push_back(pre[s.x][s.y]);
  75.         s = prePoint[s.x][s.y];
  76.     }
  77.  
  78.     reverse(path.begin(), path.end());
  79.     cout << path.size() << "\n";
  80.  
  81.     for (int it:path)
  82.     {
  83.         cout << index[it] << "\n";
  84.     }
  85.  
  86. }
  87.  
  88. int main()
  89. {
  90.     //freopen("input.txt", "r", stdin);
  91.     cin >> s >> t;
  92.     start = toPoint(s);
  93.     finish = toPoint(t);
  94.     BFS(start);
  95.     return 0;
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement