-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.h
92 lines (66 loc) · 1.8 KB
/
Graph.h
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <map>
#include <algorithm>
#include "Node.h"
#pragma once
using namespace std;
class Graph {
private:
map<int,Node> nodes;
public:
Graph(int size) {
for (int nodeID = 0; nodeID < size; nodeID++)
nodes[nodeID] = Node();
}
void addEdge(int fromNodeID, int toNodeID) {
nodes[fromNodeID].addEdge(toNodeID);
}
string toString() {
string output;
for (auto& pair: nodes) {
output += "R" + to_string(pair.first) + ":" + pair.second.toString() + "\n";
}
return output;
}
// dfsForest to get the post order of the reverse graph
stack<int> dfsForest() {
stack<int> postOrder;
set<int> visited;
for (auto& pair: nodes) {
if (visited.find(pair.first) == visited.end())
dfs(pair.first, visited, postOrder);
}
return postOrder;
}
void dfs(int nodeID, set<int>& visited, stack<int>& postOrder) {
visited.insert(nodeID);
for (int edge: nodes[nodeID].getEdges()) {
if (visited.find(edge) == visited.end())
dfs(edge, visited, postOrder);
}
postOrder.push(nodeID);
}
// dfs to get the strongly connected components
vector<vector<int>> dfsForest(stack<int>& postOrder) {
vector<vector<int>> sccs;
set<int> visited;
while (!postOrder.empty()) {
int nodeID = postOrder.top(); // fix this?
postOrder.pop();
if (visited.find(nodeID) == visited.end()) {
vector<int> scc;
dfs(nodeID, visited, scc);
sort(scc.begin(), scc.end());
sccs.push_back(scc);
}
}
return sccs;
}
void dfs(int nodeID, set<int>& visited, vector<int>& scc) {
visited.insert(nodeID);
scc.push_back(nodeID);
for (int edge: nodes[nodeID].getEdges()) {
if (visited.find(edge) == visited.end())
dfs(edge, visited, scc);
}
}
};