60std::vector<std::vector<int>>
boruvkas(std::vector<std::vector<int>> adj) {
61 size_t size = adj.size();
62 size_t total_groups = size;
70 std::vector<std::vector<int>> MST(size, std::vector<int>(size, INT_MAX));
71 for (
int i = 0; i < size; i++) {
79 std::vector<std::pair<int, int>> parent(size, std::make_pair(0, 0));
81 for (
int i = 0; i < size; i++) {
87 while (total_groups > 1) {
88 std::vector<std::pair<int, int>> smallest_edge(
89 size, std::make_pair(-1, -1));
93 for (
int i = 0; i < size; i++) {
94 for (
int j = i + 1; j < size; j++) {
95 if (adj[i][j] == INT_MAX || adj[i][j] == 0) {
104 if (parentA != parentB) {
107 int start = smallest_edge[parentA].first;
108 int end = smallest_edge[parentA].second;
112 if (start == -1 || adj[i][j] < adj[start][end]) {
113 smallest_edge[parentA].first = i;
114 smallest_edge[parentA].second = j;
118 start = smallest_edge[parentB].first;
119 end = smallest_edge[parentB].second;
121 if (start == -1 || adj[j][i] < adj[start][end]) {
122 smallest_edge[parentB].first = j;
123 smallest_edge[parentB].second = i;
131 for (
int i = 0; i < size; i++) {
133 if (smallest_edge[i].first != -1) {
135 int start = smallest_edge[i].first;
136 int end = smallest_edge[i].second;
145 if (parentA == parentB) {
152 if (parent[parentA].second < parent[parentB].second) {
153 parent[parentB].first = parentA;
154 parent[parentB].second++;
156 parent[parentA].first = parentB;
157 parent[parentA].second++;
161 MST[start][end] = adj[start][end];
162 MST[end][start] = adj[end][start];
197 std::cout <<
"Starting tests...\n\n";
198 std::vector<std::vector<int>>
graph = {
199 {0, 5, INT_MAX, 3, INT_MAX}, {5, 0, 2, INT_MAX, 5},
200 {INT_MAX, 2, 0, INT_MAX, 3}, {3, INT_MAX, INT_MAX, 0, INT_MAX},
201 {INT_MAX, 5, 3, INT_MAX, 0},
203 std::vector<std::vector<int>> MST =
204 greedy_algorithms::boruvkas_minimum_spanning_tree::boruvkas(
graph);
205 assert(greedy_algorithms::boruvkas_minimum_spanning_tree::test_findGraphSum(
207 std::cout <<
"1st test passed!" << std::endl;
209 graph = {{0, 2, 0, 6, 0},
214 MST = greedy_algorithms::boruvkas_minimum_spanning_tree::boruvkas(
graph);
215 assert(greedy_algorithms::boruvkas_minimum_spanning_tree::test_findGraphSum(
217 std::cout <<
"2nd test passed!" << std::endl;