HyeLog

๋ฐฑ์ค€_17141_์—ฐ๊ตฌ์†Œ2 ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฐฑ์ค€_17141_์—ฐ๊ตฌ์†Œ2

shj718 2022. 7. 14. 19:53

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

https://www.acmicpc.net/problem/17141

 

17141๋ฒˆ: ์—ฐ๊ตฌ์†Œ 2

์ธ์ฒด์— ์น˜๋ช…์ ์ธ ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ์—ฐ๊ตฌํ•˜๋˜ ์—ฐ๊ตฌ์†Œ์— ์Šน์›์ด๊ฐ€ ์นจ์ž…ํ–ˆ๊ณ , ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ์œ ์ถœํ•˜๋ ค๊ณ  ํ•œ๋‹ค. ์Šน์›์ด๋Š” ์—ฐ๊ตฌ์†Œ์˜ ํŠน์ • ์œ„์น˜์— ๋ฐ”์ด๋Ÿฌ์Šค M๊ฐœ๋ฅผ ๋†“์„ ๊ฒƒ์ด๊ณ , ์Šน์›์ด์˜ ์‹ ํ˜ธ์™€ ๋™์‹œ์— ๋ฐ”์ด

www.acmicpc.net

 

๐Ÿงฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜

BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

๐Ÿ’ก ์•„์ด๋””์–ด

๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ๋†“์„ ์นธ์„ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ๊ณ ๋ฅธ ํ›„ BFS๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.

 

๐Ÿ‘ฉ‍๐Ÿ’ป ์ฝ”๋“œ

#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] != 1) {
				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] = 0;
		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) {
				// 2์ธ ์นธ๋„ ๊ฒฐ๊ตญ ๋นˆ์นธ์ด๋ฏ€๋กœ 0 ๋„ฃ๊ธฐ
				a[i][j] = 0;
				candi.push_back(make_pair(i, j));
			}
		}
	}
	// ๋ฐ”์ด๋Ÿฌ์Šค ๋†“์„ ์นธ ๊ณ ๋ฅด๊ธฐ
	putVirus(0, 0);
	cout << ans << '\n';
	return 0;
}