๋ฌธ์ ๋งํฌ
https://school.programmers.co.kr/learn/courses/30/lessons/72415
์นด๋ ๋ค์ง๊ธฐ ๊ฒ์์์ ๋ชจ๋ ์นด๋์ ์ง์ ๋ง์ถ๋ ๋ฐ ํ์ํ ์ต์ ์ปค์ ์ด๋ ํ์๋ฅผ ๋ฆฌํดํ์.
ํ์ด
์ด๋์ ์ด๋ค ์นด๋๊ฐ ์๋ ์ง๋ ์ด๋ฏธ ์๊ณ ์์ง๋ง, ์ด๋ค ์นด๋๋ถํฐ ๋ค์ง์ด์ผ ๊ฐ์ฅ ์ ์ ํ์๋ก ๋ชจ๋ ์นด๋์ ์ง์ ๋ง์ถ ์ ์๋ ์ง๋ ์ ์ ์๋ค.
๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ค ํด๋ณด๊ณ ์ต์ ํ์๋ฅผ ๊ตฌํด์ค๋ค.
๋ณด๋๊ฐ 4 X 4 ํฌ๊ธฐ๋ก ๊ทธ๋ฆฌ ํฌ์ง ์๊ธฐ ๋๋ฌธ์ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ๋ค ํด๋ด๋ ์๊ฐ์ด๊ณผ๊ฐ ๋์ง ์๋๋ค.
next_permuation() ํจ์๋ฅผ ์ด์ฉํด์ ์นด๋ ๋ค์ง๋ ์์๋ฅผ ์ ํด์ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ค ํด๋ณผ ์ ์๋๋ก ํ๋ค.
์นด๋๊ฐ 1, 2, 3 ์ธ ์ข ๋ฅ๊ฐ ์๋ค๊ณ ํ์. ๋ง์ฝ ์์ด์ ํตํด ๋์จ ์์๊ฐ 2, 1, 3 ์ด๋ฉด
2๋ฒ, 1๋ฒ, 3๋ฒ ์นด๋ ์์๋๋ก ์ง์ ๋ง์ถฐ์ค๋ค.
ํ์ฌ ์ปค์ ์์น์์ ์ํ๋ ๋ฒํธ์ ์นด๋๊น์ง ์ด๋ ํ์๋ bfsํ์์ ์ด์ฉํด์ ์ฐพ๋๋ค.
์ด๋ํ ์ ์๋ ๊ฒฝ์ฐ์ ์๋ ์ต๋ 8๊ฐ์ง๋ก
←, ↑, ↓, → : ์ํ์ข์ฐ 1์นธ์ฉ ์ด๋ (4๊ฐ์ง)
[Ctrl] + ←, ↑, ↓, → : ์ํ์ข์ฐ ์ฌ๋ฌ์นธ ์ด๋(4๊ฐ์ง)
์ํ๋ ์นด๋๋ฅผ ๋ฐ๊ฒฌํ๋ฉด ๊ทธ ์ฆ์ ํ์์ ์ข ๋ฃํ๊ณ ์ด๋ ํ์๋ฅผ ๋ฆฌํดํ๋ค.
์ด๋ Enterํค๋ฅผ ๋๋ฅด๋ ๊ฒ๊น์ง ์๊ฐ ํด์ผํ๊ธฐ ๋๋ฌธ์, ํ์ํด์ ์ฐพ์ ์ด๋ ํ์์ + 1์ ํด์ ๋ฆฌํดํด์ค๋ค.
์ฝ๋ ์์ฑ
|
#include <bits/stdc++.h>
using namespace std;
pair<int,int> cursor;
vector<vector<int>> Board;
bool visited[5][5];
int dy[] = {1,0,-1,0};
int dx[] = {0,1,0,-1};
bool is_ok(pair<int,int> pos){
if(pos.first < 0 || pos.first >= 4 || pos.second < 0 || pos.second >= 4)
return false;
return true;
}
int bfs(int ed){
queue<pair<pair<int,int>,int>> q;
q.push({cursor, 0});
memset(visited, false, sizeof(visited));
while(!q.empty()){
pair<int,int> now = q.front().first;
int move = q.front().second;
q.pop();
if(visited[now.first][now.second])
continue;
visited[now.first][now.second] = true;
if(Board[now.first][now.second] == ed){
cursor = now;
Board[cursor.first][cursor.second] = 0;
return move + 1; // + Enter
}
for(int i = 0; i<4; i++){ //1์นธ์ฉ ์ด๋
pair<int,int> next = {now.first + dy[i], now.second + dx[i]};
if(is_ok(next) && !visited[next.first][next.second])
q.push({next, move + 1});
}
for(int i = 0; i<4; i++){//ctrl๋ก ์ด๋
pair<int,int> next = {now.first, now.second};
while(is_ok({next.first + dy[i], next.second + dx[i]})){
next.first += dy[i];
next.second += dx[i];
if(Board[next.first][next.second] && !visited[next.first][next.second])
break;
}
q.push({next, move + 1});
}
}
}
int solution(vector<vector<int>> board, int r, int c) {
int answer = 987654321;
vector<int> cards;
for(auto v : board)
for(auto i : v)
if(i) cards.push_back(i);
sort(cards.begin(), cards.end());
cards.erase(unique(cards.begin(), cards.end()), cards.end());
do{
cursor = {r, c};
Board = board;
int temp = 0;
for(auto card : cards){
temp += bfs(card);
temp += bfs(card);
}
answer = min(temp, answer);
}while(next_permutation(cards.begin(), cards.end()));
return answer;
}
|
cs |
'ํ๋ก๊ทธ๋๋จธ์ค > 3๋จ๊ณ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค Lv3] : ๋ธ๋ก ์ด๋ํ๊ธฐ (0) | 2022.07.25 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค Lv3] : ์ง๊ฒ๋ค๋ฆฌ ๊ฑด๋๊ธฐ (0) | 2022.07.20 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv3] : ๊ธฐ๋ฅ๊ณผ ๋ณด ์ค์น (0) | 2022.07.19 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv3] : ๊ฒฝ์ฃผ๋ก ๊ฑด์ค (0) | 2022.07.14 |
[ํ๋ก๊ทธ๋๋จธ์ค Lv3] : ํฉ์น ํ์ ์๊ธ (0) | 2022.07.13 |