Solution (오답)
- dfs를 사용해서 일단 조합을 구현하였다. 조합을 사용해서 활성화 시킬 바이러스 M개가 선택되었을 때, 해당 M개를 모두 priority queue에 넣은 후 bfs를 사용하였다.
- 처음 제출에서는 오답이었는데 그 이유는 활성 바이러스가 비활성 바이러스를 만났을 때, 비활성 바이러스가 활성 바이러스로 변하는 조건을 제대로 체크하지 않았기 때문이다.
Solution (정답)
- 바이러스가 있는 칸은 활성이든 비활성이든 빈 공간으로 치지 않는 것이 주요 포인트였다. 그래서 마지막에 이중 포문을 돌면서 빈 공간을 모두 꽉 채우는데 까지 걸린 시간을 구하는 과정에서 바이러스가 있는 칸은 해당 계산에서 제외해주었다.
연구소 3
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <limits.h>
#include <string>
#include <stack>
#include <list>
#include <unordered_set>
#include <sstream>
#include <deque>
#include <math.h>
#include <map>
#include <set>
using namespace std;
int N, M;
int arr[51][51];
vector<pair<int, int>> virus;
vector<pair<int, int>> selected_virus;
int visited[51][51];
int dy[4] = {1, 0, -1, 0};
int dx[4] = {0, 1, 0, -1};
int minimum = INT_MAX;
void bfs()
{
priority_queue<pair<int, int>> q;
for (int i = 0; i < selected_virus.size(); i++)
{
int y = selected_virus[i].first;
int x = selected_virus[i].second;
visited[y][x] = 1;
q.push({y, x});
}
while (!q.empty())
{
int y = q.top().first;
int x = q.top().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int py = y + dy[i];
int px = x + dx[i];
if (py < 0 || px < 0 || py >= N || px >= N)
{
continue;
}
if (visited[py][px] > visited[y][x] + 1 && arr[py][px] == 0)
{
visited[py][px] = visited[y][x] + 1;
q.push({py, px});
}
if (visited[py][px] == INT_MAX && arr[py][px] == 2)
{
visited[py][px] = visited[y][x]+1;
q.push({py, px});
}
}
}
}
void dfs(int depth, int start)
{
if (depth == M)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
visited[i][j] = INT_MAX;
}
}
bfs();
bool possible = true;
int maximum = 0;
for (int i = 0; i < N; i++)
{
if (!possible)
{
break;
}
for (int j = 0; j < N; j++)
{
if (visited[i][j] == INT_MAX && arr[i][j] == 0)
{
possible = false;
break;
}
else
{
if(visited[i][j] == INT_MAX || arr[i][j] == 2){
continue;
}
maximum = max(maximum, visited[i][j] - 1);
}
}
}
if(possible)
{
minimum = min(minimum, maximum);
}
}
for (int i = start; i < virus.size(); i++)
{
selected_virus.push_back(virus[i]);
dfs(depth + 1, i + 1);
selected_virus.pop_back();
}
}
void Solution()
{
dfs(0, 0);
if(minimum == INT_MAX){
cout << -1 << '\n';
}
else{
cout << minimum;
}
}
void Input()
{
cin >> N >> M;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cin >> arr[i][j];
if (arr[i][j] == 2)
{
virus.push_back({i, j});
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
Input();
Solution();
}