-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1525.cpp
75 lines (68 loc) · 1.5 KB
/
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
65
66
67
68
69
70
71
72
73
74
75
// 1525. 퍼즐
// 2020.09.25
// BFS
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<queue>
using namespace std;
int dx[] = { 0, 0, 1, -1 };
int dy[] = { 1, -1, 0, 0 };
int ans;
int main()
{
int num = 0;
int a;
for (int i = 0; i < 9; i++)
{
cin >> a;
if (a == 0)
{
a = 9;
}
num = num * 10 + a;
}
map<int, int> puzzle;
puzzle.insert({ num,0 });
queue<int> q;
q.push(num);
while (!q.empty())
{
int curNum = q.front();
string now = to_string(curNum);
q.pop();
int idx = now.find('9');
// idx의 위치를 0,0~3,3사이로 바꿔준다.
int x = idx / 3;
int y = idx % 3;
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || yy < 0 || xx >= 3 || yy >= 3)
{
continue;
}
string next = now;
// 퍼즐 이동
swap(next[x * 3 + y], next[xx * 3 + yy]);
int nextNum = stoi(next);
// 아직 방문하지 않았다면 + 1 해서 맵에 저장
if (puzzle.count(nextNum) == 0)
{
puzzle[nextNum] = puzzle[curNum] + 1;
q.push(nextNum);
}
}
}
if (puzzle.count(123456789) == 0)
{
cout << -1 << '\n';
}
else
{
cout << puzzle[123456789] << '\n';
}
return 0;
}