Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <stack>
- #include <cctype>
- #include <stdlib.h>
- #include <set>
- #include <string>
- #include <vector>
- #include <deque>
- #include <array>
- using namespace std;
- struct Puzzle
- {
- array<array<int, 3>, 3> board;
- int step;
- };
- using State = array<array<int, 3>, 3>;
- int main()
- {
- int n;
- cin >> n;
- State ans = {1,2,3,4,5,6,7,8,0};
- while(n--)
- {
- set<State> explored;
- deque<Puzzle> que;
- //bool done = false;
- Puzzle test;
- test.step = 0;
- for (int i = 0; i < 3; i++)
- {
- for (int j = 0; j < 3; j++)
- {
- cin >> test.board[i][j];
- }
- }
- que.push_back(test);
- int way[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
- while (!que.empty())
- {
- Puzzle cur = que.front();
- que.pop_front();
- if (cur.board == ans)
- {
- cout << "You can solve it within " << cur.step << " steps." << "\n";
- break;
- }
- else if (cur.step > 14)
- {
- cout << "You'd better skip this game." << endl;
- break;
- }
- int x,y,tx,ty;
- for (int i = 0; i < 3; i++)
- {
- for (int j = 0; j < 3; j++)
- {
- if (cur.board[i][j] == 0)
- {
- x = i;
- y = j;
- }
- }
- }
- for (int i = 0; i < 4; i++)
- {
- tx = x + way[i][0];
- ty = y + way[i][1];
- if (tx > 2 || ty > 2 || tx < 0 || ty < 0)
- continue;
- Puzzle newpuzzle = cur;
- newpuzzle.step = cur.step + 1;
- newpuzzle.board[x][y] = newpuzzle.board[tx][ty];
- newpuzzle.board[tx][ty] = 0;
- if (explored.find(newpuzzle.board) == explored.end())
- {
- //cout << "!!!!";
- explored.insert(newpuzzle.board);
- que.push_back(newpuzzle);
- }
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement