Algorithm

[C++/๋ฐฑ์ค€] 22352. ํ•ญ์ฒด ์ธ์‹

bba_dda 2021. 9. 14. 20:26
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

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

 

22352๋ฒˆ: ํ•ญ์ฒด ์ธ์‹

์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” SP ์ดฌ์˜ ๊ฒฐ๊ณผ์˜ ํฌ๊ธฐ๋ฅผ ์˜๋ฏธํ•˜๋Š” ๋‘ ์ •์ˆ˜ $N$๊ณผ $M$์ด ์ฃผ์–ด์ง„๋‹ค. ($1 \le N, M \le 30$) ์ด๋Š” ์ดฌ์˜ ๊ฒฐ๊ณผ๊ฐ€ ์„ธ๋กœ๋กœ $N$์นธ, ๊ฐ€๋กœ๋กœ $M$์นธ ํฌ๊ธฐ์˜ ๊ฒฉ์ž๋ผ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. ๋‹ค์Œ $N$๊ฐœ์˜ ์ค„์—๋Š”

www.acmicpc.net

ํ’€์ด

๋‘ ๋ฐฐ์—ด(before์™€ after)์„ (0, 0)๋ถ€ํ„ฐ ํ•œ ์นธ์”ฉ ๋น„๊ตํ•˜๋ฉด์„œ, ๊ฐ’์ด ๋‹ค๋ฅผ ๋•Œ BFS๋ฅผ ์‹คํ–‰ํ•ด์„œ before๋ฐฐ์—ด์˜ ๊ฐ’์„ after๋ฐฐ์—ด์˜ ๊ฐ’์œผ๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค. 

์ด๋ ‡๊ฒŒ BFS๋ฅผ ๋Œ๋ฆฌ๊ณ  ๋‚˜์„œ๋„ ๋‘ ๋ฐฐ์—ด์— ๊ฐ’์ด ๋‹ค๋ฅธ ์นธ์ด ์žˆ๋‹ค๋ฉด, NO์ด๊ณ  ์•„๋‹ˆ๋ฉด YES์ด๋‹ค. 

 

์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€, BFS๋ฅผ "๋”ฑ ํ•œ ๋ฒˆ" ๋Œ๋ ค์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. 

์•„๋ž˜ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด ์‰ฝ๊ฒŒ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋‹ค. ์•„๋ž˜ ์˜ˆ์‹œ์˜ ๋‹ต์€ NO์ด๋‹ค. ๋‘ ๋ฐฐ์—ด์€ ๊ตฌ์—ญ์€ ๋™์ผํ•˜๊ฒŒ ๋‚˜๋‰˜์–ด์ ธ ์žˆ์ง€๋งŒ, ๊ตฌ์—ญ์„ ์ฑ„์šฐ๊ณ  ์žˆ๋Š” ์ˆซ์ž๊ฐ€ ๋‹ค๋ฅธ ๋ถ€๋ถ„์ด ๋‘ ๊ตฐ๋ฐ์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ์— BFS๋ฅผ ์—ฌ๋Ÿฌ๋ฒˆ ๋Œ๋ฆฌ๊ฒŒ ํ•œ๋‹ค๋ฉด ๋‘ ๋ฐฐ์—ด์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ๋Š” YES๊ฐ€ ๋‚˜์˜ค๊ฒŒ ๋œ๋‹ค. ๋”ฐ๋ผ์„œ BFS๋ฅผ ํ•œ ๋ฒˆ๋งŒ ๋Œ๋ฆฌ๋„๋ก ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค. 

2 2 2 1        3 3 3 1

2 2 1 2        3 3 1 3

2 1 2 2        3 1 3 3 

1 2 2 2        1 3 3 3

  

์ฝ”๋“œ

#include <iostream>
#include <queue>

using namespace std;

int before[31][31];
int after[31][31];
bool visited[31][31];
int N, M;

int dr[4] = { -1,1,0,0 };
int dc[4] = { 0,0,-1,1 };

void BFS(int r, int c, int num, int target) {
	visited[r][c] = 1;
	queue<pair<int, int>> q;
	q.push({ r, c });
	while (!q.empty()) {
		int tempR = q.front().first;
		int tempC = q.front().second;
		q.pop();
		before[tempR][tempC] = target;
		for (int i = 0; i < 4; i++) {
			int nextR = tempR + dr[i];
			int nextC = tempC + dc[i];
			if (nextR < 0 || nextR >= N || nextC < 0 || nextC >= M) continue;
			if (!visited[nextR][nextC] && before[nextR][nextC] == num) {
				visited[nextR][nextC] = 1;
				q.push({ nextR, nextC });
			}
		}
	}
}

int main() {
	cin >> N >> M;
	for (int n = 0;n < N;n++) {
		for (int m = 0;m < M;m++) {
			cin >> before[n][m];
		}
	}
	for (int n = 0;n < N;n++) {
		for (int m = 0;m < M;m++) {
			cin >> after[n][m];
		}
	}
	bool flag = 1; //BFS๋ฅผ ๋”ฑ ํ•œ๋ฒˆ๋งŒ ๋Œ๋ฆฌ๊ธฐ ์œ„ํ•จ 
	for (int n = 0;n < N;n++) {
		for (int m = 0;m < M;m++) {
			if (before[n][m] != after[n][m] && flag) {
				BFS(n, m, before[n][m], after[n][m]);
				flag = 0;
			}
		}
	}
	bool result = 1;
	// ๊ฒ€์‚ฌ
	for (int n = 0; n < N; n++) {
		for (int m = 0; m < M; m++)
			if (before[n][m] != after[n][m])
				result = 0;
	}
	if (result) cout << "YES" << endl;
	else cout << "NO" << endl;
	return 0;
}

๊ฒฐ๊ณผ

๋ฐ˜์‘ํ˜•