๋์ด๋ : ๊ณจ๋ 2
๊ฑธ๋ฆฐ ์๊ฐ : 1์๊ฐ
๋ฌธ์
3×3 ํ์ ๋ค์๊ณผ ๊ฐ์ด ์๊ฐ ์ฑ์์ ธ ์๋ค. ์ค๋ฅธ์ชฝ ์๋ ๊ฐ์ฅ ๋ ์นธ์ ๋น์ด ์๋ ์นธ์ด๋ค.
1 | 2 | 3 |
---|---|---|
4 | 5 | 6 |
7 | 8 |
์ด๋ค ์์ ์ธ์ ํด ์๋ ๋ค ๊ฐ์ ์นธ ์ค์ ํ๋๊ฐ ๋น์ด ์์ผ๋ฉด, ์๋ฅผ ๊ทธ ์นธ์ผ๋ก ์ด๋์ํฌ ์๊ฐ ์๋ค. ๋ฌผ๋ก ํ ๋ฐ๊นฅ์ผ๋ก ๋๊ฐ๋ ๊ฒฝ์ฐ๋ ๋ถ๊ฐ๋ฅํ๋ค. ์ฐ๋ฆฌ์ ๋ชฉํ๋ ์ด๊ธฐ ์ํ๊ฐ ์ฃผ์ด์ก์ ๋, ์ต์์ ์ด๋์ผ๋ก ์์ ๊ฐ์ ์ ๋ฆฌ๋ ์ํ๋ฅผ ๋ง๋๋ ๊ฒ์ด๋ค.
ํ์ด
- ์ต๋จ ๊ฒฝ๋ก ๋ฌธ์ ์ด๋ฏ๋ก bfs ์ด์ฉ
- memo ํด์ผ ๋๊ฐ์ ๊ฒฝ๋ก ๋ค์ ํ์ x
- memo๋ ์ ์ฒด map์ ์ํ๋ฅผ ์ ์ฅํด์ผํจ
- string์ผ๋ก ์ ์ฅ
์ฝ๋
#include <iostream>
#include <string>
#include <unordered_set>
#include <algorithm>
#include <queue>
using namespace std;
int map[10];
unordered_set<string> memo;
int direction[9][4] = { {-1,1,3,-1}, {-1,2,4,0}, {-1,-1,5,1}, {0,4,6,-1}, {1,5,7,3}, {2,-1,8,4}, {3,7,-1,-1}, {4,8,-1,6}, {5,-1,-1,7} };
struct Node {
int zero;
string mapstring;
int move = 0;
Node(int z, string s, int m) {
zero = z;
mapstring = s;
move = m;
}
};
int main() {
int zero = -1;
string mapString = "";
for (int i = 0; i < 9; i++) {
string tmp = "";
cin >> tmp;
mapString += tmp;
if (tmp == "0")
zero = i;
}
if (mapString == "123456780") {
cout << 0;
return 0;
}
queue<Node*> que;
que.push(new Node(zero, mapString, 0)); memo.insert(mapString);
while (!que.empty()) {
Node* z = que.front(); que.pop();
for (int i = 0; i < 4; i++) {
if (direction[z->zero][i] == -1)
continue;
int zeroSpot = z->zero; string tmpMapString = z->mapstring; int tmpMove = z->move +1;
int newZero = direction[z->zero][i];
tmpMapString[z->zero] = tmpMapString[newZero];
tmpMapString[newZero] = '0';
if (tmpMapString == "123456780") { // ์ ๋ต
cout << tmpMove;
return 0;
}
auto pos = memo.find(tmpMapString);
if (pos != memo.end())// memo์ ์๋ค๋ฉด (๋ฐฉ๋ฌธ ํ๋ ๊ณณ์ด๋ฉด)
continue;
que.push(new Node(newZero, tmpMapString, tmpMove));
memo.insert(tmpMapString);
}
}
cout << -1;
}
memo๋ unordered_set์ ์ด์ฉํด์ string์ผ๋ก ํ๋จ
์ฃผ์ํ ์
- dfs๋ก ํ๋ฉด ์คํ ์ค๋ฒํ๋ก์ฐ
- ์ฒ์์ ์ ๋ต์ด ๋์ด์ค๋ ๊ฒฝ์ฐ 0์ ์ถ๋ ฅํด์ฃผ์ด์ผ ํจ
๊ฒฐ๊ณผ
์์ด๋ | ๋ฉ๋ชจ๋ฆฌ | ์๊ฐ | ์ธ์ด | ์ฝ๋ ๊ธธ์ด |
---|---|---|---|---|
gmldms784 | 27780 | 192 | C++17 / ์์ | 2553 |
๋ฐ์ํ
'Algorithm ๋ฌธ์ > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[c++] BOJ 1194 :: ๋ฌ์ด ์ฐจ์ค๋ฅธ๋ค ๊ฐ์ (0) | 2021.06.02 |
---|---|
[c++] BOJ 2250 :: ํธ๋ฆฌ์ ๋์ด์ ๋๋น (0) | 2021.06.02 |
[c++] BOJ 9019 :: DSLR (0) | 2021.05.26 |
[c++] BOJ 2146 :: ๋ค๋ฆฌ ๋ง๋ค๊ธฐ (0) | 2021.05.18 |
[c++] BOJ 2589 :: ๋ณด๋ฌผ์ฌ (0) | 2021.05.18 |
Comment