#include
#include
#include
using namespace std;
const int MAX = 51;
int n, m;
int way[MAX][MAX];
vector<pair<int, int>> chicken;
int answer = 987654321;
int chickensize = 0;
//가는거 안가는거 다 dfs 가기, 치킨집 갯수 되면 끝
void dfs(int counts, string bit) {
int chickenpath = 0;
int chickenway = 0;
int flag = 0;
int onenum = 0;
for (int i = 0; i < bit.length(); i++) {
if (bit[i] == '1')
onenum++;
}
if (onenum <= m && bit.length() == chickensize) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
chickenway = 987654321;
if (way[i][j] == 1) {
for (int k = 0; k < counts; k++) {
if (bit[k] == '1') {
chickenway = min(chickenway, abs(chicken[k].first - i) + abs(chicken[k].second - j));
flag = 1;
}
}
if (flag == 1) {
chickenpath += chickenway;
}
}
}
}
if (flag == 1) {
answer = min(answer, chickenpath);
flag = 0;
}
return;
}
if (bit.length() == chickensize)
return;
dfs(counts + 1, bit + '0');
dfs(counts + 1, bit + '1');
}
int main(void) {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> way[i][j];
if (way[i][j] == 2) {
chicken.push_back(make_pair(i, j));
chickensize++;
}
}
}
dfs(0,"");
cout << answer << endl;
return 0;
}
'백준 알고리즘 > 브루트포스' 카테고리의 다른 글
사다리 조작 C++ (0) | 2021.10.22 |
---|---|
백준 2048 (Easy) C++ (0) | 2019.10.19 |
백준 14502번 C++ (0) | 2019.04.09 |
백준 1018번 C++ (0) | 2019.02.04 |
백준 14889번 C++ (0) | 2019.01.28 |