์ฝ”๋”ฉํ…Œ์ŠคํŠธ/BOJ

[๋ฐฑ์ค€1012] ์œ ๊ธฐ๋† ๋ฐฐ์ถ”(C++)

kite707 2021. 7. 8.

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

 

1012๋ฒˆ: ์œ ๊ธฐ๋† ๋ฐฐ์ถ”

์ฐจ์„ธ๋Œ€ ์˜๋†์ธ ํ•œ๋‚˜๋Š” ๊ฐ•์›๋„ ๊ณ ๋žญ์ง€์—์„œ ์œ ๊ธฐ๋† ๋ฐฐ์ถ”๋ฅผ ์žฌ๋ฐฐํ•˜๊ธฐ๋กœ ํ•˜์˜€๋‹ค. ๋†์•ฝ์„ ์“ฐ์ง€ ์•Š๊ณ  ๋ฐฐ์ถ”๋ฅผ ์žฌ๋ฐฐํ•˜๋ ค๋ฉด ๋ฐฐ์ถ”๋ฅผ ํ•ด์ถฉ์œผ๋กœ๋ถ€ํ„ฐ ๋ณดํ˜ธํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๊ธฐ ๋•Œ๋ฌธ์—, ํ•œ๋‚˜๋Š” ํ•ด์ถฉ ๋ฐฉ์ง€์— 

www.acmicpc.net

#include <iostream>
using namespace std;


int T, M, N, K;
int map[60][60];
int moveX[4] = { 0,1,0,-1 };
int moveY[4] = { 1,0,-1,0 };

void reset() {
	for (int i = 0; i < 60; i++) {
		for (int j = 0; j < 60; j++) {
			map[i][j] = 0;
		}
	}
}

void dfs(int a, int b) {
	if (map[a][b] == 1) {
		map[a][b] = 0;
		for (int i = 0; i < 4; i++) {
			int mx = a + moveX[i];
			int my = b + moveY[i];
			//๋ฒ”์œ„ ๋ฒ—์–ด๋‚˜์ง€ ์•Š์œผ๋ฉด ๋ฐฉ๋ฌธ
			if (mx >= 0 && my >= 0 && mx < M && my <= N) {
				dfs(mx, my);
			}
		}
	}
}
int main() {
	ios::sync_with_stdio(false);
    cin.tie(0);

	cin >> T;
	while (T--) {
		int ans = 0;
		cin >> M >> N >> K;
		while (K--) {
			int x, y;
			cin >> x >> y;
			map[x][y] = 1;

		}
		for (int i = 0; i < M; i++) {
			for (int j = 0; j < N; j++) {
				if (map[i][j] == 1) {
					dfs(i,j);
					ans++;

				}
			}
		}


		cout << ans << "\n";
		reset();
	}
}

 

๋‹ค์‹œ ํ‘ผ ์ฝ”๋“œ

#include <iostream>
#include <vector>
using namespace std;

int arr[52][52];
int T;
int M, N, K;
int a, b;
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,-1,0,1 };
int count_cata = 0;
void cata(int x,int y) {

	if (arr[x][y] == 1) {
		arr[x][y] = 0;
		for (int pos = 0; pos < 4; pos++) {
			int mx = x + dx[pos];
			int my = y + dy[pos];
			cata(mx, my);
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	cin >> T;
	while (T--) {
		cin >> M >> N >> K;
		for (int i = 1; i <= K; i++) {
			cin >> a >> b;
			arr[a + 1][b + 1] = 1;
		}
		for (int xx = 1; xx <= M; xx++) {
			for (int yy = 1; yy <= N; yy++) {
				if (arr[xx][yy] == 1) {
					cata(xx, yy);
					count_cata++;
				}
				
			}
		}
		cout << count_cata << "\n";

		count_cata = 0;
		for (int i = 0; i < 52; i++) {
			for (int jjj = 0; jjj < 52; jjj++) {
				arr[i][jjj] = 0;
			}
		}
	}
}

๋Œ“๊ธ€