97%에서 실패했었다... 이때 반례가
5 2
1 1 1 1 1
1 1 2 1 1
1 1 2 1 1
1 1 1 1 1
1 1 1 1 1
처럼 처음부터 바이러스가 퍼졌을 때는, 시간이 0초이다. 따라서 BFS를 다 돌리고 난 다음, dist의 max값을 구해주었다.
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <tuple>
using namespace std;
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int n, m;
vector<pair<int, int>> vir;
int bfs(vector<vector<int>>& map, queue<pair<int, int>>& Q) {
int x, y;
int dist[51][51];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = -1;
}
}
for (int i = 0; i < Q.size(); i++) {
tie(x, y) = Q.front(); Q.pop();
dist[x][y] = 0;
Q.push(make_pair(x, y));
}
while (!Q.empty()) {
tie(x, y) = Q.front(); Q.pop();
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= n || xx < 0 || yy >= n || yy < 0) continue;
if (map[xx][yy] == 1) continue;
if (dist[xx][yy] == -1) {
dist[xx][yy] = dist[x][y] + 1;
Q.push(make_pair(xx, yy));
}
}
}
int ans = -1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j] == 1) continue;
if (dist[i][j] == -1) {
return -1;
}
else if (ans < dist[i][j]) {
ans = dist[i][j];
}
}
}
//cout << ans << '\n';
return ans;
}
int main() {
freopen("in1.txt", "rt", stdin);
cin >> n >> m;
vector<vector<int>> map(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> map[i][j];
if (map[i][j] == 2) {
vir.push_back(make_pair(i, j));
//cout << i << " " << j << " " << '\n';
}
}
}
vector<int> comb;
for (int i = 0; i < m; i++) {
comb.push_back(1);
}
for (int i = 0; i < vir.size() - m; i++) {
comb.push_back(0);
}
int ans = -1;
sort(comb.begin(), comb.end());
do {
queue<pair<int, int>> Q;
for (int i = 0; i < comb.size(); i++) {
if (comb[i] == 1) {
Q.push(make_pair(vir[i].first, vir[i].second));
//cout << vir[i].first << " " << vir[i].second << " " << '\n';
}
}
//cout << '\n';
int tmp = bfs(map, Q);//bfs
if (ans==-1||(tmp < ans&&tmp!=-1)) {
ans = tmp;
//cout << ans<< " "<<"tmp"<<tmp << '\n';
}
} while (next_permutation(comb.begin(), comb.end()));
cout << ans << '\n';
return 0;
}