728x90
[๋ฌธ์ ]
[ํ์ด]
๋ฒกํฐ๋ฅผ ํ์ฉํ ์ธ์ ๋ฆฌ์คํธ์ DFS๋ก ํ~!
*๋์ ํ ๋น๋ถ๋ถ ๊ธฐ์ตํ๊น ...
vector<int> *graph = new vector<int>[vertexNum + 1]; //์ธ์ ๋ฆฌ์คํธ ๋์ ํ ๋น
bool *visited = new bool[vertexNum + 1];
[ํ์ด ์ฝ๋]
#include <iostream>
#include <vector>
using namespace std;
void dfs(int vertex, vector<int> graph[], bool *visited);
int main() {
int vertexNum, edgeNum, u, v;
cin >> vertexNum >> edgeNum;
vector<int> *graph = new vector<int>[vertexNum + 1]; //์ธ์ ๋ฆฌ์คํธ ๋์ ํ ๋น
bool *visited = new bool[vertexNum + 1];
for (int i = 0; i < edgeNum; i++) {
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
for (int i = 0; i < vertexNum; i++) visited[i] = false;
int count = 0;
for (int i = 1; i <= vertexNum; i++) {
if (!visited[i]) {
dfs(i, graph, visited);
count++;
}
}
cout << count;
delete[] visited;
return 0;
}
void dfs(int vertex, vector<int> graph[], bool *visited) {
visited[vertex] = true;
for (int i = 0; i < graph[vertex].size(); i++) {
if (!visited[graph[vertex][i]]) dfs(graph[vertex][i], graph, visited);
}
}
728x90
'๐ Coding Test Study > Algorithm Problem' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++][Programmers][์ ๋ ฌ] K๋ฒ์งธ ์ (0) | 2023.04.19 |
---|---|
[C++][Beakjoon][DFS/BFS] 13023๋ฒ ABCDE (0) | 2022.05.10 |
[C++][Baekjoon][๋นํธ๋ง์คํฌ] 11723๋ฒ ์งํฉ (0) | 2022.05.08 |
[C++][Baekjoon] 10971๋ฒ ์ธํ์ ์ํ2 (0) | 2022.05.08 |
[C++][Baekjoon][Math] 6588๋ฒ ๊ณจ๋๋ฐํ์ ์ถ์ธก(feat. C++ ์ ์ถ๋ ฅ ์๊ฐ ๋จ์ถ) (0) | 2022.04.03 |