Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <queue>
- #include <set>
- #include <queue>
- using namespace std;
- using ll = long long;
- int dy[4] = {1,0,-1,0}, dx[4] = {0,1,0,-1};
- int shift[4] = {-12,-4,12,4};
- int main() {
- ll start = 0, dest = 0;
- for(int i=0; i<9; ++i) {
- ll a;
- scanf("%lld",&a);
- start += (a<<i*4);
- }
- for(int i=1; i<9; ++i) {
- dest += ((ll)i<<(4 * (i-1)));
- }
- set<ll> visited;
- queue<ll> q;
- q.push(start);
- int ret = 0;
- while(!q.empty()) {
- ll qs = q.size();
- while(qs--) {
- ll cur = q.front();
- q.pop();
- if(cur == dest) {
- printf("%d\n",ret);
- return 0;
- }
- ll pos0 = 0;
- for(;cur & (15LL << pos0 * 4); pos0++);
- ll y = pos0/3, x = pos0%3;
- // printf("%lld %lld\n",r,c);
- for(int i=0; i<4; ++i) {
- ll ny = y + dy[i], nx = x + dx[i];
- if(ny < 0 || ny >= 3 || nx < 0 || nx >= 3) continue;
- //temp: 0으로 만들고자 하는 위치의 cur의 bit
- ll temp = cur & (15LL <<(ny*3+nx)*4);
- //cur의 0000 부분과 다음 상태의 0000부분이 0000인 상태
- ll next = cur - temp;
- //
- if(shift[i] > 0) temp <<= shift[i];
- else temp >>= -shift[i];
- next += temp;
- if(visited.find(next) == visited.end()) {
- visited.insert(next);
- q.push(next);
- }
- }
- }
- ++ret;
- }
- puts("-1");
- }
Add Comment
Please, Sign In to add comment