https://www.acmicpc.net/problem/1012
#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;
}
}
}
}
'์ฝ๋ฉํ ์คํธ > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค1978]-์์ ์ฐพ๊ธฐ(C++) (0) | 2021.07.18 |
---|---|
[๋ฐฑ์ค2609]-์ต๋๊ณต์ฝ์์ ์ต์๊ณต๋ฐฐ์(C++)/์ ํด๋ฆฌ๋ ํธ์ ๋ฒ (0) | 2021.07.18 |
[๋ฐฑ์ค1260]DFS์ BFS(C++) (0) | 2021.07.03 |
[๋ฐฑ์ค10989]-์ ์ ๋ ฌํ๊ธฐ 3(C++) (0) | 2021.06.23 |
[๋ฐฑ์ค2309] - ์ผ๊ณฑ๋์์ด(C++) (0) | 2021.01.11 |
๋๊ธ