#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 9;
int office[MAX][MAX];
int n, m;
int copyoffice[MAX][MAX];
int answer = 987654321;
vector<int> angle;
vector<pair<int, int>> camera;
vector<int> cameraangle[5];
struct Move {
int x, y;
};
Move mv[4] = { {-1,0}, {0,1}, {1,0}, {0,-1} };
void copyandmincheck() {
int value = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (copyoffice[i][j] == 0)
value++;
copyoffice[i][j] = office[i][j];
}
}
answer = min(answer, value);
return;
}
void dfs(int i) {
if (angle.size() == camera.size()) {
for (int k = 0; k < camera.size(); k++) {
int shift = angle[k];
for (int j = 0; j < cameraangle[office[camera[k].first][camera[k].second]-1].size(); j++) {
int moveangle = cameraangle[office[camera[k].first][camera[k].second] - 1][j] + shift;
if (moveangle >= 4)
moveangle -= 4;
int movex = camera[k].first;
int movey = camera[k].second;
while (1) {
if (copyoffice[movex][movey] == 6 || movex <0 || movex >=n || movey <0 || movey >=m)
break;
else {
if (copyoffice[movex][movey] == 0)
copyoffice[movex][movey] = -1;
}
movex += mv[moveangle].x;
movey += mv[moveangle].y;
}
}
}
copyandmincheck();
return;
}
for (int k = 0; k < 4; k++) {
angle.push_back(k);
dfs(i + 1);
angle.pop_back();
}
}
int main(void) {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> office[i][j];
copyoffice[i][j] = office[i][j];
if (office[i][j] >= 1 && office[i][j] <= 5)
camera.push_back(make_pair(i, j));
}
}
cameraangle[0].push_back(1);
cameraangle[1].push_back(1);
cameraangle[1].push_back(3);
cameraangle[2].push_back(0);
cameraangle[2].push_back(1);
cameraangle[3].push_back(1);
cameraangle[3].push_back(0);
cameraangle[3].push_back(3);
cameraangle[4].push_back(0);
cameraangle[4].push_back(1);
cameraangle[4].push_back(2);
cameraangle[4].push_back(3);
dfs(0);
cout << answer << endl;
return 0;
}
'백준 알고리즘 > DFS' 카테고리의 다른 글
백준 사다리 조작 C++ (0) | 2019.10.19 |
---|---|
백준 미세먼지 안녕 C++ (0) | 2019.10.15 |
백준 12100번 C++ (0) | 2019.09.19 |
백준 2468번 C++ (0) | 2019.02.25 |
백준 2667번 C++ (0) | 2019.02.25 |