HyeLog

๋ฐฑ์ค€_17142_์—ฐ๊ตฌ์†Œ3 ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฐฑ์ค€_17142_์—ฐ๊ตฌ์†Œ3

shj718 2022. 7. 14. 20:30

๐Ÿ™‹‍โ™€๏ธ ๋ฌธ์ œ

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;
}