Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(1012) 유기농 배추 본문

백준 (C++)/Solve

(1012) 유기농 배추

dh-winternagi 2026. 4. 18. 23:15

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