-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_basic.cpp
More file actions
69 lines (57 loc) · 1.12 KB
/
graph_basic.cpp
File metadata and controls
69 lines (57 loc) · 1.12 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAX = 100005;
vector<int> adj[MAX];
bool visited[MAX];
// DFS (재귀)
void dfs(int cur) {
visited[cur] = true;
cout << cur << " ";
for (int next : adj[cur]) {
if (!visited[next]) {
dfs(next);
}
}
}
// BFS (큐)
void bfs(int start) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int cur = q.front();
q.pop();
cout << cur << " ";
for (int next : adj[cur]) {
if (!visited[next]) {
visited[next] = true;
q.push(next);
}
}
}
}
// 위상 정렬 (Kahn's Algorithm)
vector<int> topologicalSort(int n, vector<int> &indegree) {
queue<int> q;
vector<int> result;
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0)
q.push(i);
}
while (!q.empty()) {
int cur = q.front();
q.pop();
result.push_back(cur);
for (int next : adj[cur]) {
indegree[next]--;
if (indegree[next] == 0)
q.push(next);
}
}
if (result.size() != n)
return {}; // 사이클 존재
return result;
}