๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์˜ค๋Š˜์˜ ์‚ฝ์งˆ

[ALGO] ๋ฐ˜ํ™˜ํ˜•์„ ๋ช…ํ™•ํžˆ ํ•˜์ž

by nitronium102 2023. 6. 20.

๋ฌธ์ œ

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

 

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

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

www.acmicpc.net

 

๋‚˜์˜ ์‚ฝ์งˆ

์ž๊พธ ๋งž๋Š” ์ฝ”๋“œ์ธ๋ฐ ์ด์ƒํ•˜๊ฒŒ ํ์—์„œ (0, 0)์ด ๋ฌดํ•œ์ •์œผ๋กœ ์ƒ์„ฑ๋ผ์„œ ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค

1) ์ธ์ž๋กœ char color๋ฅผ ๋„˜๊ธฐ๊ณ  board[nx][ny] != color๋กœ ๋น„๊ตํ•ด์„œ ๊ทธ๋Ÿฐ๊ฐ€ ๊ณ ๋ฏผ

2) const int MAX๋ฅผ ์จ์„œ ๊ทธ๋Ÿฐ๊ฐ€ ๊ณ ๋ฏผ

 

๊ฒฐ๋ก 

๋‹ค ์“ธ๋ฐ์—†์—ˆ๊ณ  bfs ํ•จ์ˆ˜ ๋ฐ˜ํ™˜ํ˜•์ด void์ธ๋ฐ int๋กœ ํ•ด์„œ ๊ทธ๋Ÿฐ ๊ฑฐ์˜€๋‹ค.

์•„๋‹ˆ ๋ฐ˜ํ™˜ํ˜•์ด int์ธ๋ฐ ์™œ ํ์— ๊ฐ’์ด ๋“ค์–ด๊ฐ€๋Š” ๊ฑด์ง€ ์ดํ•ดํ•  ์ˆ˜ ์—†๋„ค

 

์‹ฌ์ง€์–ด ์ด๊ฒŒ reple.it์—์„œ๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋‚˜์˜ค๋Š”๋ฐ clion์—์„œ๋Š” ๋ณด์ •์ด ๋˜๋Š” ๋ชจ์–‘์ธ์ง€ ๊ฐ’์ด ์ž˜ ๋‚˜์™€์„œ ๋” ํ—ท๊ฐˆ๋ฆฌ๊ฒŒ ํ–ˆ๋‹ค

์•ž์œผ๋กœ๋Š” repl.it์„ ์ ๊ทน ์ด์šฉํ•ด์•ผ๊ฒ ๋‹ค ^.^ 

#include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> ci;
const int MAX = 101;

char board[MAX][MAX];
bool visited[MAX][MAX];
int n;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};

void bfs(int a, int b) {
	queue<ci> q;

  q.push({a, b});
	visited[a][b] = true;

	while (!q.empty()) {
		int x = q.front().first;
		int y = q.front().second;
		q.pop();

		for (int i = 0; i < 4; i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];

			if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
			if (visited[nx][ny] || (board[nx][ny] != board[a][b])) continue;
			visited[nx][ny] = true;
			q.push({nx, ny});
		}
	}
}

int findArea() {
	int answer = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (!visited[i][j]) {
				bfs(i, j);
				answer++;
			}
		}
	}
	return answer;
}

int main() {
	// ์‹œ๊ฐ„ ์ดˆ๊ณผ
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> n;

	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			cin >> board[i][j];

	int normal = findArea();

	// visited ์ดˆ๊ธฐํ™”
	for (int i = 0; i < n; i++)
		fill(visited[i], visited[i] + n, false);

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (board[i][j] == 'G')
				board[i][j] = 'R';
		}
	}

	int abnormal = findArea();

	// ์ถœ๋ ฅ
	cout << normal << ' ' << abnormal;
}

๋Œ“๊ธ€