#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 9;
int n, m;
int map[MAX][MAX];
int copys[MAX][MAX];
vector<pair<int, int>> camera;
int visited[MAX][MAX][4];
int answer = 987654321;
vector<int> angle;
struct Move {
int x, y;
};
Move mv[4] = { {0,1}, {-1,0}, {0,-1}, {1,0} };
void copymap() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = copys[i][j];
}
}
}
void calanswer() {
int value = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == 0)
value++;
}
}
answer = min(answer, value);
}
void dfs(int count) {
if (count == camera.size()) {
for (int i = 0; i < camera.size(); i++) {
int currenti = camera[i].first;
int currentj = camera[i].second;
for (int k = 0; k < 4; k++) {
if (visited[currenti][currentj][k] == 1) {
int movei = currenti + mv[(angle[i] + k)%4].x;
int movej = currentj + mv[(angle[i] + k)%4].y;
while (true) {
if (map[movei][movej] == 6)
break;
if (!(movei >= 0 && movei < n && movej >= 0 && movej < m))
break;
if(map[movei][movej] == 0)
map[movei][movej] = -1;
movei = movei + mv[(angle[i] + k)%4].x;
movej = movej + mv[(angle[i] + k)%4].y;
}
}
}
}
calanswer();
copymap();
return;
}
for (int i = 0; i < 4; i++) {
angle.push_back(i);
dfs(count + 1);
angle.pop_back();
}
return;
}
int main(void) {
cin >> n >> m;
memset(visited, -1, sizeof(visited));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
copys[i][j] = map[i][j];
if (map[i][j] == 1) {
visited[i][j][0] = 1;
camera.push_back(make_pair(i, j));
}
else if (map[i][j] == 2) {
visited[i][j][0] = 1;
visited[i][j][2] = 1;
camera.push_back(make_pair(i, j));
}
else if (map[i][j] == 3) {
visited[i][j][0] = 1;
visited[i][j][1] = 1;
camera.push_back(make_pair(i, j));
}
else if (map[i][j] == 4) {
visited[i][j][0] = 1;
visited[i][j][1] = 1;
visited[i][j][2] = 1;
camera.push_back(make_pair(i, j));
}
else if (map[i][j] == 5) {
visited[i][j][0] = 1;
visited[i][j][1] = 1;
visited[i][j][2] = 1;
visited[i][j][3] = 1;
camera.push_back(make_pair(i, j));
}
}
}
dfs(0);
cout << answer << endl;
return 0;
}
'백준 알고리즘 > DFS' 카테고리의 다른 글
마법사 상어와 파이어스톰 C++ (0) | 2021.02.28 |
---|---|
원판 돌리기 C++ (0) | 2021.02.28 |
백준 사다리 조작 C++ (0) | 2019.10.19 |
백준 미세먼지 안녕 C++ (0) | 2019.10.15 |
백준 15683번 C++ (0) | 2019.09.19 |