문제
https://www.acmicpc.net/problem/14502
풀이
- 재귀함수를 통해 벽 3개를 추가한다.
- 벽이 3개가 쌓였을 때 BFS를 통해 바이러스를 퍼트리고 안전영역의 크기를 구한다.
- 1로 돌아가 반복한다
소스코드
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
#define MAX_N 9
int n, m;
int map[MAX_N][MAX_N];
int temp_map[MAX_N][MAX_N];
int ans;
int dx[4] = { 0,0,-1,1 };
int dy[4] = { -1,1,0,0 };
vector<pair<int, int>> virus;
vector<int> safety_Zone;
void CopyMap(int(*a)[MAX_N], int(*b)[MAX_N])
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = b[i][j];
}
void BfsVirus()
{
int after_Wall[MAX_N][MAX_N];
CopyMap(after_Wall, temp_map);
queue<pair<int, int>> q;
for (int i = 0; i < virus.size(); i++) q.push(virus[i]);
while (!q.empty())
{
int x = q.front().first, y = q.front().second;
q.pop();
for (int k = 0; k < 4; k++)
{
int nx = x + dx[k], ny = y + dy[k];
if (0 <= nx && nx < n && 0 <= ny && ny < m)
{
if (after_Wall[nx][ny] == 0)
{
after_Wall[nx][ny] = 2;
q.push(make_pair(nx, ny));
}
}
}
}
int safety_Size = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (after_Wall[i][j] == 0)
safety_Size++;
}
}
ans = ans > safety_Size ? ans : safety_Size;
}
void RecurWall(int cnt)
{
if (cnt == 3)
{
BfsVirus();
return;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (temp_map[i][j] == 0)
{
temp_map[i][j] = 1;
RecurWall(cnt + 1);
temp_map[i][j] = 0;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> map[i][j];
if (map[i][j] == 2)
virus.push_back(make_pair(i, j));
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
if (map[i][j] == 0)
{
CopyMap(temp_map, map);
temp_map[i][j] = 1;
RecurWall(1);
temp_map[i][j] = 0;
}
}
}
cout << ans << "\n";
return 0;
}