Problem Solving/BOJ [백준 1012번] [DFS / BFS] 유기농 배추 - 728x90 반응형 Approach 연결 요소(Component)의 개수를 묻는 문제이다. 배추가 심어져 있는 곳에 대해서 방문하지 않았다면 DFS / BFS를 돌리고 component의 개수를 1 증가시켜 주면 된다. Code #include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0) using namespace std; typedef pair<int, int> pii; int dx[4] = {0, 0, 1, -1}; int dy[4] = {-1, 1, 0, 0}; int m, n; int edge[51][51]; int visited[51][51]; vector<pii> node; void dfs(int x_val, int y_val){ visited[x_val][y_val] = 1; for(int i = 0; i < 4; i++){ int x = x_val + dx[i]; int y = y_val + dy[i]; if(x < 0 || x > m || y < 0 || y > n) continue; if(!visited[x][y] && edge[x][y] == 1) dfs(x, y); } return; } int main(void){ fastio; int t; cin >> t; while(t--){ memset(edge, 0, sizeof(edge)); memset(visited, 0, sizeof(visited)); node.clear(); int k; cin >> m >> n >> k; for(int i = 0; i < k; i++){ int x, y; cin >> x >> y; edge[x][y] = 1; node.push_back(make_pair(x, y)); } int component = 0; for(int i = 0; i < node.size(); i++){ int cur_x = node[i].first; int cur_y = node[i].second; if(!visited[cur_x][cur_y]){ dfs(cur_x, cur_y); component++; } } cout << component << "\n"; } return 0; } 반응형 공유하기 URL 복사카카오톡 공유페이스북 공유엑스 공유 게시글 관리 구독하기비룡의 컴퓨터이야기 Contents Approach Code 당신이 좋아할만한 콘텐츠 [백준 11724번] [DFS] 연결 요소의 개수 2021.12.10 [백준 9466번] [DFS / Cycle] 팀 프로젝트 2021.12.10 [백준 6549번] [스택] 히스토그램에서 가장 큰 직사각형 2021.12.09 [백준 1725번] [스택] 히스토그램 2021.12.09 댓글 0 + 이전 댓글 더보기