Notice
Recent Posts
Recent Comments
Link
Be a developer
백준 11724 연결 요소의 개수 본문
각 정점을 돌면서 bfs를 돌리면 된다.
필요 없는 실행을 줄이기 위해서 bfs들어가기 전 방문했는지 check 배열을 통해 알아본다.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include <iostream> #include <vector> #include <algorithm> #include <cstring> #include <queue> using namespace std; int n, m, ans; bool check[1000000]; vector<int> g[1001]; void bfs(int x) { queue<int> q; //처음 넣는 node를 check해야 한다. check[x] = true; q.push(x); while (!q.empty()) { int current = q.front(); q.pop(); for (int i = 0; i < g[current].size(); i++) { int next = g[current][i]; if (!check[next]) { check[next] = true; q.push(next); } } } } int main(int argc, char** argv) { cin >> n >> m; for (int i = 0; i < m; i++) { int from, to; cin >> from >> to; //양방향으로 넣기 g[from].push_back(to); g[to].push_back(from); } for (int i = 1; i <= n; i++) { if (!check[i]) { ans++; bfs(i); } } printf("%d\n", ans); return 0; } | cs |
'알고리즘' 카테고리의 다른 글
백준 2667 단지번호붙이기 (0) | 2019.04.07 |
---|---|
백준 1707 이분 그래프 (0) | 2019.04.07 |
백준 1260 DFS와 BFS (0) | 2019.04.05 |
백준 15652 N과 M (4) (0) | 2019.04.04 |
백준 15651 N과 M (3) (0) | 2019.04.04 |
Comments