HyeLog

๋ฐฑ์ค€_10026_์ ๋ก์ƒ‰์•ฝ ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฐฑ์ค€_10026_์ ๋ก์ƒ‰์•ฝ

shj718 2022. 7. 2. 21:48

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

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

 

10026๋ฒˆ: ์ ๋ก์ƒ‰์•ฝ

์ ๋ก์ƒ‰์•ฝ์€ ๋นจ๊ฐ„์ƒ‰๊ณผ ์ดˆ๋ก์ƒ‰์˜ ์ฐจ์ด๋ฅผ ๊ฑฐ์˜ ๋Š๋ผ์ง€ ๋ชปํ•œ๋‹ค. ๋”ฐ๋ผ์„œ, ์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ์€ ์•„๋‹Œ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ๊ณผ๋Š” ์ข€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ๋‹ค. ํฌ๊ธฐ๊ฐ€ N×N์ธ ๊ทธ๋ฆฌ๋“œ์˜ ๊ฐ ์นธ์— R(๋นจ๊ฐ•), G(์ดˆ๋ก)

www.acmicpc.net

 

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

์ตœ์†Œ(์ตœ๋‹จ)๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๊ฐ€ ์•„๋‹ˆ๋ฏ€๋กœ BFS, DFS ๋‘˜๋‹ค ์‚ฌ์šฉ ๊ฐ€๋Šฅ (๋‚˜๋Š” BFS๋กœ ํ’€์—ˆ๋‹ค.)

์ •์ : ํฌ๊ธฐ๊ฐ€ N×N์ธ ๊ทธ๋ฆฌ๋“œ์˜ ๊ฐ ์นธ

๊ฐ„์„ : ์นธ → ์นธ

 

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

-์ด๋™ ๊ฐ€๋Šฅํ•œ ์ •์ ์ธ์ง€ ์ฒดํฌํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๊ตฌํ˜„.

-์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์„ ์œ„ํ•œ ํ•จ์ˆ˜, ์•„๋‹Œ ์‚ฌ๋žŒ์„ ์œ„ํ•œ ํ•จ์ˆ˜ 2๊ฐœ๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ํ•˜๋‚˜์˜ ํ•จ์ˆ˜๋กœ ์ฒ˜๋ฆฌ. (๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ ๋ก์ƒ‰์•ฝ ์—ฌ๋ถ€ ์ „๋‹ฌ)

-๊ตฌ์—ญ์˜ ๊ฐœ์ˆ˜ = BFS์˜ ์‹œ์ž‘ ํšŸ์ˆ˜

 

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

#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

int dx[4] = { 0,0,-1,1 };
int dy[4] = { -1,1,0,0 };

bool can(bool blind, char from, char to) { // ์ด๋™ ๊ฐ€๋Šฅํ•œ ์ •์ ์ธ์ง€ ํ™•์ธํ•˜๋Š” ํ•จ์ˆ˜
	if (from == to) return true;
	if (blind) {
		if (from == 'R' && to == 'G') return true;
		if (from == 'G' && to == 'R') return true;
	}
	return false;
}

int solve(vector<string> &a, bool blind = false) {
	// ์ดˆ๊ธฐํ™”
	int n = a.size();
	vector<vector<bool>> visited(n, vector<bool>(n, false));
	int ans = 0; // ๊ตฌ์—ญ ๊ฐœ์ˆ˜

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (visited[i][j] == false) {
				// ๊ตฌ์—ญ ์ฆ๊ฐ€์‹œํ‚ค๊ธฐ
				ans += 1;
				// BFS
				queue<pair<int, int>> q;
				q.push(make_pair(i, j));
				visited[i][j] = true;

				while (!q.empty()) {
					auto cur = q.front();
					q.pop();

					for (int i = 0; i < 4; i++) {
						int nx = cur.first + dx[i];
						int ny = cur.second + dy[i];

						if (nx >= 0 && nx < n && ny >= 0 && ny < n) { // ๋ฒ”์œ„ ์ฒดํฌ
							if (visited[nx][ny] == false && can(blind, a[cur.first][cur.second], a[nx][ny])) { // ๋ฐฉ๋ฌธ ์—ฌ๋ถ€, ์ƒ‰๊น” ์ฒดํฌ
								q.push(make_pair(nx, ny));
								visited[nx][ny] = true;
							}
						}
					}
				}
			}
		}
	}
	return ans;
}

int main() {
	// input
	int n;
	cin >> n;
	vector<string> a(n);
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}

	// solve, output
	cout << solve(a) << ' ' << solve(a, true) << '\n';
	return 0;
}