[백준] 14502 연구소
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int N,M;
int board[101][101] = { 0 };
vector<pair<int, int>> virus;
int maxSafe = -1;
bool inRange(int r, int c) {
if (r < 0 || r >= N) return false;
if (c < 0 || c >= M) return false;
return true;
}
int dirR[4] = { 0, 0, 1, -1 };
int dirC[4] = { 1, -1, 0, 0 };
int getSafe() {
int visited[101][101] = { 0 };
queue<pair<int, int>> q;
for (int i = 0; i < virus.size(); ++i) {
q.push(virus[i]);
}
while (!q.empty()) {
int curR = q.front().first;
int curC = q.front().second;
q.pop();
if (visited[curR][curC]) continue;
visited[curR][curC] = 1;
for (int d = 0; d < 4; ++d) {
int nextR = curR + dirR[d];
int nextC = curC + dirC[d];
if (!inRange(nextR, nextC)) continue;
if (visited[nextR][nextC]) continue;
if (board[nextR][nextC] == 1) continue;
q.push({ nextR, nextC });
}
}
int safe = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if ((board[i][j] == 0) && (visited[i][j] == 0))
safe++;
}
}
return safe;
}
void chooseWall(int wallCnt) {
if (wallCnt == 3) {
maxSafe = max(maxSafe, getSafe());
return;
}
for (int r = 0; r < N; ++r) {
for (int c = 0; c < M; ++c) {
if (board[r][c] == 0){
board[r][c] = 1;
chooseWall(wallCnt + 1);
board[r][c] = 0;
}
}
}
return;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> N >> M;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
int input;
cin >> input;
board[i][j] = input;
if (board[i][j] == 2) {
virus.push_back({i, j});
}
}
}
chooseWall(0);
cout << maxSafe;
return 0;
}