알고리즘
백준 18405번 경쟁적 전염 C++
영춘권의달인
2021. 11. 21. 12:10
bfs 탐색을 통하여 해결할 수 있는 문제이다. bfs문제 중에서는 어려운 편에 속하는 것 같다.
k개의 큐를 만들고, 각각의 큐를 낮은 숫자부터 한 칸씩만 탐색하여 문제를 해결하였다.
좌표와 카운트를 담는 k개의 큐를 벡터에 넣어서 사용하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int PosRow[4] = { -1,0,1,0 };
int PosCol[4] = { 0,1,0,-1 };
int n, k;
cin >> n >> k;
vector < queue<pair<pair<int, int>, int>>> virus(k + 1);
vector<vector<int>> v(n + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> v[i][j];
if (v[i][j] != 0) {
virus[v[i][j]].push({ {i,j},0 });
}
}
}
int s, x, y;
cin >> s >> x >> y;
for (int i = 0; i < s; i++) {
for (int j = 1; j <= k; j++) {
while (true) {
if (virus[j].empty()) break;
auto a = virus[j].front();
if (a.second > i)break;
virus[j].pop();
for (int y = 0; y < 4; y++) {
int nextRow = a.first.first + PosRow[y];
int nextCol = a.first.second + PosCol[y];
if (nextRow<1 || nextRow>n) continue;
if (nextCol<1 || nextCol>n) continue;
if (v[nextRow][nextCol] == 0) {
v[nextRow][nextCol] = j;
virus[j].push({ {nextRow,nextCol},a.second + 1 });
}
}
}
}
}
cout << v[x][y];
};