๋ฌธ์
https://www.acmicpc.net/problem/2606
๋ฌธ์ ์ดํด
- ์ปดํจํฐ๊ฐ ๋ฐ์ด๋ฌ์ค์ ๊ฑธ๋ฆฌ๋ฉด, ๊ทธ ์ปดํจํฐ์ ๋คํธ์ํฌ ์์์ ์๋ก ์ฐ๊ฒฐ๋์ด ์๋ ์ปดํจํฐ๋ ๋ชจ๋ ๋ฐ์ด๋ฌ์ค์ ๊ฑธ๋ฆฐ๋ค.
- 1๋ฒ ์ปดํจํฐ๋ฅผ ํตํด ๋ฐ์ด๋ฌ์ค์ ๊ฑธ๋ฆฌ๊ฒ ๋๋ ์ปดํจํฐ์ ์ ์ถ๋ ฅ
๋ฌธ์ ํ์ด
๐ ์ ๊ทผ
- ๋คํธ์ํฌ ์์์ ์ฐ๊ฒฐ๋์ด ์๋ ์ปดํจํฐ๋ค์ ๊ทธ๋ํ๋ก ๋ํ๋ผ ์ ์๋ค.
- 1๋ฒ ์ปดํจํฐ์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ์ปดํจํฐ๋ฅผ ํ์ํ๋ค.
๐ก DFS & BFS
- ์ธ์ ํ๋ ฌ์ ๋คํธ์ํฌ ์์์ ์๋ก ์ฐ๊ฒฐ๋์ด ์๋ ์ปดํจํฐ์ ์ ๋ณด๋ฅผ ์ ์ฅํ๋ค.
- 1๋ฒ ์ปดํจํฐ๋ถํฐ ํ์์ ์์ํด์, 1๋ฒ ์ปดํจํฐ์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ์ปดํจํฐ์ ๋ฐฉ๋ฌธํ๋ค.
- ๋ฐฉ๋ฌธํ ๋๋ง๋ค ๋ฐฉ๋ฌธ ํ์๋ฅผ ํ๊ณ ์นด์ดํธ(๋ฐ์ด๋ฌ์ค์ ๊ฑธ๋ฆฌ๋ ์ปดํจํฐ์ ์)๋ฅผ ์ฆ๊ฐ์ํจ๋ค.
์ฝ๋
1๏ธโฃ DFS
#include <iostream>
#include <vector>
using namespace std;
int n, m, cnt;
vector<vector<bool> > adj;
vector<bool> visited;
void dfs(int com) {
visited[com] = true;
cnt++;
for (int next = 1; next < n + 1; next++) {
if (adj[com][next] && !visited[next])
dfs(next);
}
}
int main() {
// ์
๋ ฅ
cnt = 0;
cin >> n >> m;
adj.assign(n + 1, vector<bool>(n + 1, false));
visited.assign(n + 1, false);
for (int i = 0; i < m; i++) {
int r, c;
cin >> r >> c;
adj[r][c] = true;
adj[c][r] = true;
}
// ์ฐ์ฐ
dfs(1);
// ์ถ๋ ฅ
cout << cnt - 1;
return 0;
}
2๏ธโฃ BFS
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, m;
vector<vector<bool> > adj;
vector<bool> visited;
int bfs(int com) {
int cnt = 0;
queue<int> q;
q.push(com);
visited[com] = true;
while (!q.empty()) {
com = q.front();
cnt++;
q.pop();
for (int next = 1; next < n + 1; next++) {
if (!adj[com][next] || visited[next])
continue;
visited[next] = true;
q.push(next);
}
}
return cnt - 1;
}
int main() {
// ์
๋ ฅ
cin >> n >> m;
adj.assign(n + 1, vector<bool>(n + 1, false));
visited.assign(n + 1, false);
for (int i = 0; i < m; i++) {
int r, c;
cin >> r >> c;
adj[r][c] = true;
adj[c][r] = true;
}
// ์ฐ์ฐ & ์ถ๋ ฅ
cout << bfs(1);
return 0;
}
'๐ญ Problem Solving > C++' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ][C++] ๋ฐฑ์ค 12865๋ฒ: ํ๋ฒํ ๋ฐฐ๋ญ (0) | 2025.05.19 |
---|---|
[BOJ][C++] ๋ฐฑ์ค 11559๋ฒ: Puyo Puyo (0) | 2025.05.18 |
[BOJ][C++] ๋ฐฑ์ค 1303๋ฒ: ์ ์ - ์ ํฌ (0) | 2025.04.23 |
[BOJ][C++] ๋ฐฑ์ค 1890๋ฒ: ์ ํ (0) | 2025.04.23 |
[BOJ][C++] ๋ฐฑ์ค 2579๋ฒ: ๊ณ๋จ์ค๋ฅด๊ธฐ (0) | 2025.04.23 |