HyeLog
๋ฐฑ์ค_17142_์ฐ๊ตฌ์3 ๋ณธ๋ฌธ
๐โ๏ธ ๋ฌธ์
https://www.acmicpc.net/problem/17142
17142๋ฒ: ์ฐ๊ตฌ์ 3
์ธ์ฒด์ ์น๋ช ์ ์ธ ๋ฐ์ด๋ฌ์ค๋ฅผ ์ฐ๊ตฌํ๋ ์ฐ๊ตฌ์์ ์น์์ด๊ฐ ์นจ์ ํ๊ณ , ๋ฐ์ด๋ฌ์ค๋ฅผ ์ ์ถํ๋ ค๊ณ ํ๋ค. ๋ฐ์ด๋ฌ์ค๋ ํ์ฑ ์ํ์ ๋นํ์ฑ ์ํ๊ฐ ์๋ค. ๊ฐ์ฅ ์ฒ์์ ๋ชจ๋ ๋ฐ์ด๋ฌ์ค๋ ๋นํ์ฑ ์ํ์ด๊ณ
www.acmicpc.net
๐งฉ ์๊ณ ๋ฆฌ์ฆ
BFS ์๊ณ ๋ฆฌ์ฆ
๐ก ์์ด๋์ด
๋ฐ์ด๋ฌ์ค๋ฅผ ๋์ ์นธ์ ์ฌ๊ทํจ์๋ก ๊ณ ๋ฅธ ํ BFS๋ฅผ ์ํํ๋ค.
์ฐ๊ตฌ์2 ๋ฌธ์ ์ ๊ฑฐ์ ๋น์ทํ์ง๋ง, ๋นํ์ฑํ ๋ฐ์ด๋ฌ์ค๊ฐ ์์ผ๋ฏ๋ก ๋ง์ง๋ง์ ๋ต์ ๊ตฌํ ๋ ์ด ๊ฒฝ์ฐ๋ ์ ์ธํ๊ณ ๋น ์นธ์ ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆฐ ์ต์ ์๊ฐ๋ง ๊ตฌํด์ผ ํ๋ค.
๐ฉ๐ป ์ฝ๋
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
#include <tuple>
using namespace std;
int n, m;
int a[50][50];
int dist[50][50];
int dx[4] = { 0,-1,0,1 };
int dy[4] = { -1,0,1,0 };
vector<pair<int, int>> candi;
int ans = -1;
void bfs() {
// BFS
memset(dist, -1, sizeof(dist));
queue<pair<int, int>> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == 3) {
q.push(make_pair(i, j));
dist[i][j] = 0;
}
}
}
while (!q.empty()) {
int x, y;
tie(x, y) = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (0 <= nx && nx < n && 0 <= ny && ny < n) { // ๋ฒ์ ์ฒดํฌ
if (a[nx][ny] != 1 && dist[nx][ny] == -1) { // ๋ฒฝ, ๋ฐฉ๋ฌธ ์ฌ๋ถ ์ฒดํฌ
dist[nx][ny] = dist[x][y] + 1;
q.push(make_pair(nx, ny));
}
}
}
}
// ์ต์ ์๊ฐ ๊ตฌํ๊ธฐ
int cur = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (a[i][j] == 0) { // ๋น์นธ์ ํผ๋จ๋ฆฌ๋ ์ต์์๊ฐ์ ๊ตฌํด์ผ ํจ (๋นํ์ฑํ๋ฅผ ํ์ฑํ์ํจ๊ฑด ํฌํจ X)
if (dist[i][j] == -1) return; // ๋ชจ๋ ๋น ์นธ์ ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆด ์ ์๋ ๊ฒฝ์ฐ
if (cur < dist[i][j]) cur = dist[i][j];
}
}
}
if (ans == -1 || ans > cur) {
ans = cur;
}
}
void putVirus(int index, int cnt) {
if (index == candi.size()) {
if (cnt == m) {
bfs(); // ๋ค ๋์์ผ๋ฉด BFS
}
}
else {
int x, y;
tie(x, y) = candi[index];
a[x][y] = 3;
putVirus(index + 1, cnt + 1);
a[x][y] = 2; // ๋นํ์ฑ ๋ฐ์ด๋ฌ์ค๋ก ์์๋ณต๊ตฌ
putVirus(index + 1, cnt);
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
// input
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
if (a[i][j] == 2) {
candi.push_back(make_pair(i, j));
}
}
}
// ๋ฐ์ด๋ฌ์ค ๋์ ์นธ ๊ณ ๋ฅด๊ธฐ
putVirus(0, 0);
cout << ans << '\n';
return 0;
}
'์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฐฑ์ค_11060_์ ํ ์ ํ (0) | 2022.08.02 |
---|---|
๋ฐฑ์ค_11048_์ด๋ํ๊ธฐ (0) | 2022.08.02 |
๋ฐฑ์ค_17141_์ฐ๊ตฌ์2 (0) | 2022.07.14 |
๋ฐฑ์ค_2234_์ฑ๊ณฝ (0) | 2022.07.08 |
๋ฐฑ์ค_17086_์๊ธฐ ์์ด2 (0) | 2022.07.08 |