[C++/๋ฐฑ์ค] 22352. ํญ์ฒด ์ธ์
๋ฌธ์
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;
}