[BOJ] 1525 퍼즐

Time Lapse :45min 32sec

1525.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <queue>
#include <map>
using namespace std;
int dx[4] = { 0,1,0,-1 };
int dy[4] = { -1,0,1,0 };
const int target = 123456789;
int search(int p) {
int ret = 8;
while (p) {
if (p % 10 == 9) return ret;
p *= 0.1; --ret;
}
return ret;
}
int SWAP(int x, int y, int nx, int ny, int num) {
int p[3][3];
for (int i = 2; i >= 0; --i)
for (int j = 2; j >= 0; --j)
p[i][j] = num % 10, num *= 0.1;
swap(p[y][x], p[ny][nx]);
int ret = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
ret = ret * 10 + p[i][j];
return ret;
}
int main(void) {
int puzzle = 0, n;
for (int i = 0; i < 9; ++i) {
scanf("%d", &n);
if (!n) n = 9;
puzzle = puzzle * 10 + n;
}
if (puzzle == target) { printf("0"); return 0; }
queue<int> q;
map<int, int> m;
q.push(puzzle);
m.emplace(puzzle, 0);
while (!q.empty()) {
puzzle = q.front();
q.pop();
int pos = search(puzzle);
int x = pos % 3;
int y = pos / 3;
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (0 <= nx && nx < 3 && 0 <= ny && ny < 3) {
int newpuzzle = SWAP(x, y, nx, ny, puzzle);
if (newpuzzle == target) {
printf("%d", m[puzzle] + 1);
return 0;
}
if (!m.count(newpuzzle)) {
m[newpuzzle] = m[puzzle] + 1;
q.push(newpuzzle);
}
}
}
}
printf("-1");
return 0;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/30/PS/BOJ/1525/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.