dh-winternagi 님의 블로그
(1012) 유기농 배추 본문
https://www.acmicpc.net/problem/1012
단계별로 풀어보기
27단계(그래프와 순회) 8번째

#include <iostream>
#include <vector>
using namespace std;
int solve(){
int m, n, k;
cin >> m >> n >> k;
vector v(n, vector<bool> (m));
while(k--){
int x, y;
cin >> x >> y;
v[y][x]= true;
}
int cnt= 0;
auto dfs= [&](auto self, int nowx, int nowy) -> void {
v[nowx][nowy]= false;
for(int i=0;i<4;i++){
int nextx= nowx+"0121"[i]-'1';
int nexty= nowy+"1012"[i]-'1';
if(nextx<0 || nextx>n-1 || nexty<0 || nexty>m-1) continue;
if(!v[nextx][nexty]) continue;
self(self, nextx, nexty);
}
};
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!v[i][j]) continue;
cnt++;
dfs(dfs, i, j);
}
}
return cnt;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
cin >> T;
while(T--){
cout << solve() << "\n";
}
return 0;
}'백준 (C++) > Solve' 카테고리의 다른 글
| (1697) 숨바꼭질 (0) | 2026.04.18 |
|---|---|
| (2178) 미로 탐색 (0) | 2026.04.18 |
| (2667) 단지번호붙이기 (0) | 2026.04.18 |
| (1260) DFS와 BFS (0) | 2026.04.18 |
| (2606) 바이러스 (0) | 2026.04.18 |
