※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※
이번에 볼 문제는 백준 17141번 문제인 연구소 2이다.
문제는 아래 링크를 확인하자.
https://www.acmicpc.net/problem/17141
17141번: 연구소 2
인체에 치명적인 바이러스를 연구하던 연구소에 승원이가 침입했고, 바이러스를 유출하려고 한다. 승원이는 연구소의 특정 위치에 바이러스 M개를 놓을 것이고, 승원이의 신호와 동시에 바이
www.acmicpc.net
주어진 조건 중 입력으로 주어지는 2의 개수는 10 이하라는 점에 주목하자. 이러한 경우, 바이러스를 놓을 수 있는 경우의 수는 많아야 252가지가 되므로 모든 바이러스를 놓을 수 있는 조합에 대하여 BFS를 시도해보는 것으로 문제를 해결할 수 있게 된다.
구현거리가 많은 문제이다. 구현에 유의하자.
아래는 제출한 소스코드이다.
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
int N, M, S;
int board[50][50];
vector<pair<int, int>> vir;
vector<pair<int, int>> stk;
int dist[50][50];
int dr[4] = { 1,-1,0,0 };
int dc[4] = { 0,0,1,-1 };
int ans = 1000000007;
void bfs() {
memset(dist, 0, sizeof(dist));
queue<pair<int, int>> que;
for (auto& p : stk) {
dist[p.first][p.second] = 1;
que.push(p);
}
while (!que.empty()) {
int r = que.front().first, c = que.front().second; que.pop();
for (int i = 0; i < 4; i++) {
int rr = r + dr[i], cc = c + dc[i];
if (-1 < rr && rr < N && -1 < cc && cc < N) {
if (dist[rr][cc] == 0 && board[r][c] != 1) {
dist[rr][cc] = dist[r][c] + 1;
que.push(make_pair(rr, cc));
}
}
}
}
int mx = 0; bool chk = 1;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (board[r][c] != 1) {
if (dist[r][c] == 0) chk = 0;
else mx = max(mx, dist[r][c]);
}
}
}
if (chk) ans = min(ans, mx);
}
void func(int idx) {
if (stk.size() == M) {
bfs();
return;
}
if (idx == S) return;
func(idx + 1);
stk.emplace_back(vir[idx]);
func(idx + 1);
stk.pop_back();
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
cin >> board[r][c];
if (board[r][c] == 2) vir.emplace_back(make_pair(r, c));
}
}
S = vir.size();
func(0);
if (ans == 1000000007) cout << -1;
else cout << ans - 1;
}
728x90
'BOJ' 카테고리의 다른 글
[BOJ 5938 // C++] Daisy Chains in the Field (0) | 2023.01.04 |
---|---|
[BOJ 27106 // C++] Making Change (0) | 2023.01.03 |
[BOJ 24198 // C++] Muffinspelet (0) | 2023.01.02 |
[BOJ 17142 // C++] 연구소 3 (0) | 2023.01.02 |
[BOJ 20976 // C++] 2 番目に大きい整数 (The Second Largest Integer) (0) | 2023.01.01 |