-
Notifications
You must be signed in to change notification settings - Fork 0
/
4_7.cpp
118 lines (105 loc) · 2.16 KB
/
4_7.cpp
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/*from is row, to is col. to is dep on from*/
class Graph
{
public:
Graph(int num);
void addEdge(int from, int to);
void removeEdge(int from, int to);
void removeAllEdges(int node);
bool isDependent(int node);
void print();
vector<int> build();
int num_nodes;
vector< vector<int> > adj_mat;
vector<bool> built;
};
Graph::Graph(int num) : num_nodes(num),
adj_mat(vector<vector <int> >(num,vector<int> (num,0))) ,
built(vector<bool>(num,false))
{
}
void Graph::addEdge (int from, int to)
{
adj_mat[from][to] = 1;
}
void Graph::removeEdge (int from, int to)
{
adj_mat[from][to] = 0;
}
void Graph::removeAllEdges (int node)
{
for (int i = 0; i < num_nodes; i++)
{
removeEdge(node,i);
}
}
bool Graph::isDependent (int node)
{
for (int i = 0; i < num_nodes; i++)
{
if (adj_mat[i][node] != 0)
return true;
}
return false;
}
void Graph::print()
{
for (int i = 0; i < num_nodes; i++)
{
for (int j = 0; j < num_nodes; j++)
{
cout << adj_mat[i][j] << " ";
}
cout << endl;
}
}
vector<int> Graph::build()
{
vector<int> build_order;
queue<int> q;
for (int i = 0; i < num_nodes; i++)
{
if (!isDependent(i))
{
q.push(i);
built[i] = true;
}
}
while (!q.empty())
{
int curr = q.front();
q.pop();
removeAllEdges(curr);
build_order.push_back(curr);
for (int i = 0; i < num_nodes; i++)
{
if (!built[i] && !isDependent(i))
{
q.push(i);
built[i] = true;
}
}
}
return build_order;
}
int main(int argc, char* argv[])
{
Graph g = Graph(6);
g.addEdge(0,3);
g.addEdge(5,1);
g.addEdge(1,3);
g.addEdge(5,0);
g.addEdge(3,2);
g.print();
vector<int> build_order = g.build();
for (int i = 0; i < build_order.size(); i++)
{
cout << build_order[i] << " ";
}
cout << endl;
return 0;
}