μ°μ κΈ°λ‘ πͺ
[C++ μκ³ λ¦¬μ¦] 무ν₯κ·Έλν μ¬μ΄ν΄ dfs λ³Έλ¬Έ
Computer Science/μλ£κ΅¬μ‘° & μκ³ λ¦¬μ¦
[C++ μκ³ λ¦¬μ¦] 무ν₯κ·Έλν μ¬μ΄ν΄ dfs
kite707 2025. 1. 21. 22:53dfsλ₯Ό μμ©νμ¬ λ¬΄ν₯κ·Έλνμμμ μ¬μ΄ν΄μ νλ¨ν μ μλ μ½λμ΄λ€.
κ°λ¨νκ² μ€λͺ νμλ©΄ μ μ νλμ© μννλ©° μ¬μ΄ν΄μ΄ μ‘΄μ¬νλμ§ νλ³νλ μ½λμ΄λ€.
μλ₯Ό λ€μ΄ μλμ κ°μ κ·Έλνκ° μλ€κ³ νμ.
λμΌλ‘ λ΄μλ 2 3 5 μ¬μ΄ν΄μ΄ μ‘΄μ¬ν¨μ μ μ μλ€. μλ μ½λμμλ 1μμλΆν° dfsλ₯Ό νλ©° λ°λ‘ μ¬μ΄ν΄μ μ°Ύκ² λλ€.
dfs κ°μ₯ μλ path.pop_back()μ 4μ κ°μ΄ μ¬μ΄ν΄μ ν¬ν¨λμ§ μλ λ Έλλ₯Ό μ κ±°νλ μ½λμ΄λ€. μΈμ ν λ Έλκ° μ μ λ°©λ¬Έν λ Έλλ°μ μμ λμ κ²½μ°μ΄λ€.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> graph; // κ·Έλν μΈμ 리μ€νΈ
vector<pair<int, int>> edges; // κ°μ μ 보
vector<bool> visited;
vector<int> path;
bool dfs(int cur, int prev) {
cout << "cur is " << cur << endl;
path.push_back(cur);
visited[cur] = true;
for (auto k : graph[cur]) {
if (!visited[k]) {
if (dfs(k, cur))return true;
}
else if (k != prev) {
path.push_back(k);
return true;
}
}
path.pop_back();
return false;
}
vector<int> findCycle(int n) {
for (int i = 1; i <= n; i++) {
path.clear();
vector<int> ans;
if (dfs(i, -1)) {
int start = path.back();
while (!path.empty()) {
int cur = path.back();
path.pop_back();
ans.push_back(cur);
if (cur == start && ans.size() > 1) {
return ans;
}
}
}
}
return {};
}
int main() {
int n = 6; // λ
Έλ μ
edges = { {1, 2}, {2, 3}, {3, 4}, {3, 5}, {5,2} };
visited.assign(n, false);
// κ·Έλν μ΄κΈ°ν
graph.assign(n + 1, vector<int>());
for (auto edge : edges) {
graph[edge.first].push_back(edge.second);
graph[edge.second].push_back(edge.first);
}
vector<int> vec = findCycle(n);
if (!vec.empty()) {
for (auto k : vec) {
cout << k << " ";
}
cout << endl;
}
else {
cout << "NO CYCLE\n";
}
return 0;
}
κ΄λ ¨ λ¬Έμ λ₯Ό νμ΄λ³Ό μ μλ λΈλ‘κ·Έ
'Computer Science > μλ£κ΅¬μ‘° & μκ³ λ¦¬μ¦' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[C++ μκ³ λ¦¬μ¦] νλ‘μ΄λ μκ³ λ¦¬μ¦ (0) | 2025.02.25 |
---|---|
[C++ μκ³ λ¦¬μ¦] LCS, Longest Common Subsequence (0) | 2025.02.20 |
[C++ μκ³ λ¦¬μ¦] ν΅μ λ ¬ (2) | 2024.11.26 |
[C++] λ²‘ν° νμ (0) | 2021.09.07 |
[C++] μ«μ μλ¦Ώμ λνκΈ° (0) | 2021.09.07 |