-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph-base.cpp
More file actions
101 lines (81 loc) · 2.43 KB
/
graph-base.cpp
File metadata and controls
101 lines (81 loc) · 2.43 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
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
/*
* A template for the 2019 MPI lab at the University of Warsaw.
* Copyright (C) 2016, Konrad Iwanicki.
* Refactoring 2019, Łukasz Rączkowski
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "graph-base.h"
Graph* allocateGraphPart(int numVertices, int firstRowIdxIncl, int lastRowIdxExcl) {
if (firstRowIdxIncl >= lastRowIdxExcl || firstRowIdxIncl < 0 || numVertices <= 0) {
return nullptr;
}
auto graph = new Graph;
graph->data = nullptr;
graph->extraRow = nullptr;
graph->numVertices = numVertices;
graph->firstRowIdxIncl = firstRowIdxIncl;
graph->lastRowIdxExcl = lastRowIdxExcl;
graph->data = new int *[graph->lastRowIdxExcl - graph->firstRowIdxIncl];
if (graph->data == nullptr) {
freeGraphPart(graph);
return nullptr;
}
graph->extraRow = new int[graph->numVertices];
if (graph->extraRow == nullptr) {
freeGraphPart(graph);
return nullptr;
}
int n = graph->lastRowIdxExcl - graph->firstRowIdxIncl;
for (int i = 0; i < n; ++i) {
graph->data[i] = nullptr;
}
for (int i = 0; i < n; ++i) {
graph->data[i] = new int[graph->numVertices];
if (graph->data[i] == nullptr) {
freeGraphPart(graph);
return nullptr;
}
}
return graph;
}
void initializeGraphRow(int* row, int rowIdx, int numVertices) {
for (int j = 0; j < numVertices; ++j) {
row[j] = rowIdx == j ? 0 :
#ifndef USE_RANDOM_GRAPH
((rowIdx - j == 1 || j - rowIdx == 1) ? 1 : numVertices + 5);
#else
(rand() & 8191) + 1;
#endif
}
}
void printGraphRow(int const* row, int rowIdx, int numVertices) {
std::cout << row[0];
for (int j = 1; j < numVertices; ++j) {
std::cout << " " << row[j];
}
std::cout << std::endl;
}
void freeGraphPart(Graph* graph) {
if (graph == nullptr) {
return;
}
if (graph->extraRow != nullptr) {
delete (graph->extraRow);
graph->extraRow = nullptr;
}
if (graph->data != nullptr) {
for (int i = 0, n = graph->lastRowIdxExcl - graph->firstRowIdxIncl; i < n; ++i) {
if (graph->data[i] != nullptr) {
delete (graph->data[i]);
graph->data[i] = nullptr;
}
}
delete (graph->data);
graph->data = nullptr;
}
graph->numVertices = 0;
graph->firstRowIdxIncl = 0;
graph->lastRowIdxExcl = 0;
}