Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <stack>
  4. #include <cctype>
  5. #include <stdlib.h>
  6. #include <set>
  7. #include <string>
  8. #include <vector>
  9. #include <deque>
  10. #include <array>
  11. using namespace std;
  12. struct Puzzle
  13. {
  14.     array<array<int, 3>, 3> board;
  15.     int step;
  16. };
  17. using State = array<array<int, 3>, 3>;
  18. int main()
  19. {
  20.     int n;
  21.     cin >> n;
  22.     State ans = {1,2,3,4,5,6,7,8,0};
  23.     while(n--)
  24.     {
  25.         set<State> explored;
  26.         deque<Puzzle> que;
  27.         //bool done = false;
  28.         Puzzle test;
  29.         test.step = 0;
  30.         for (int i = 0; i < 3; i++)
  31.         {
  32.             for (int j = 0; j < 3; j++)
  33.             {
  34.                 cin >> test.board[i][j];
  35.             }
  36.         }
  37.         que.push_back(test);
  38.         int way[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
  39.         while (!que.empty())
  40.         {
  41.             Puzzle cur = que.front();
  42.             que.pop_front();
  43.             if (cur.board == ans)
  44.             {
  45.                cout << "You can solve it within " << cur.step << " steps." << "\n";
  46.                break;
  47.             }
  48.             else if (cur.step > 14)
  49.             {
  50.                  cout << "You'd better skip this game." << endl;
  51.                  break;
  52.             }
  53.             int x,y,tx,ty;
  54.             for (int i = 0; i < 3; i++)
  55.             {
  56.                 for (int j = 0; j < 3; j++)
  57.                 {
  58.                     if (cur.board[i][j] == 0)
  59.                     {
  60.                        x = i;
  61.                        y = j;
  62.                     }
  63.                 }
  64.             }
  65.  
  66.             for (int i = 0; i < 4; i++)
  67.             {
  68.                 tx = x + way[i][0];
  69.                 ty = y + way[i][1];
  70.                 if (tx > 2 || ty > 2 || tx < 0 || ty < 0)
  71.                     continue;
  72.                 Puzzle newpuzzle = cur;
  73.                 newpuzzle.step = cur.step + 1;
  74.                 newpuzzle.board[x][y] = newpuzzle.board[tx][ty];
  75.                 newpuzzle.board[tx][ty] = 0;
  76.                 if (explored.find(newpuzzle.board) == explored.end())
  77.                 {
  78.                    //cout << "!!!!";
  79.                    explored.insert(newpuzzle.board);
  80.                    que.push_back(newpuzzle);
  81.  
  82.                 }
  83.  
  84.             }
  85.         }
  86.  
  87.     }
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement