트리와 그래프는 모두 정점(Vertex)과 간선(Edge)으로 구성된 자료구조
5개의 정점, 4개의 간선
정점: {0, 1, 2, 3, 4}
간선: {(0, 1), (0, 2), (1, 3), (1, 4)}
트리 조건:
5개의 정점, 5개의 간선
정점: {0, 1, 2, 3, 4}
간선: {(0, 1), (1, 2), (2, 3), (3, 0), (3, 4)}
그래프 조건:
#include <iostream>
#include <vector>
using namespace std;
bool isTree(int N, vector<pair<int, int>>& edges) {
// 트리 조건: 간선 수 == 노드 수 - 1
if (edges.size() != N - 1) return false;
// 인접 리스트 생성
vector<vector<int>> graph(N);
for (auto& edge : edges) {
graph[edge.first].push_back(edge.second);
graph[edge.second].push_back(edge.first);
}
// 사이클 및 연결 여부 확인 (DFS)
vector<bool> visited(N, false);
bool hasCycle = false;
function<void(int, int)> dfs = [&](int node, int parent) {
visited[node] = true;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, node);
} else if (neighbor != parent) {
hasCycle = true;
}
}
};
// 루트 노드(0)에서 탐색 시작
dfs(0, -1);
// 모든 노드가 연결되어 있는지 확인
for (bool v : visited) {
if (!v) return false; // 연결되지 않은 노드가 있음
}
return !hasCycle; // 사이클이 없어야 트리
}
int main() {
int N = 5; // 정점 수
vector<pair<int, int>> edges = {{0, 1}, {0, 2}, {1, 3}, {1, 4}}; // 간선 목록
if (isTree(N, edges)) {
cout << "이 그래프는 트리입니다." << endl;
} else {
cout << "이 그래프는 트리가 아닙니다." << endl;
}
return 0;
}
📌 비트 시프트 연산 (Bit Shift Operation) (0) | 2025.02.21 |
---|---|
조합과 순열//combination vs permutation (0) | 2025.02.11 |
이분 탐색 //(Binary Search) (0) | 2025.01.22 |
그리디 알고리즘 (Greedy Algorithm) (0) | 2025.01.21 |
투 포인터 알고리즘 (TwoPointers) (1) | 2025.01.21 |