-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.cpp
More file actions
117 lines (96 loc) · 2.9 KB
/
Copy pathGraph.cpp
File metadata and controls
117 lines (96 loc) · 2.9 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
102
103
104
105
106
107
108
109
110
111
112
#include "Graph.hpp"
using namespace ariel;
// Constructor implementation
Graph::Graph()
{
}
// Method to load graph from adjacency matrix
void Graph::loadGraph( std::vector<std::vector<int>> &adjacency_matrix)
{
this->isDirected = false;
this->numOfEdges = 0;
this->withWeights = false;
this->hasNegativeEdge = false;
if (adjacency_matrix.size() == 0)
{
// If the matrix is empty, the graph is empty
throw std::invalid_argument("The matrix is empty");
}
for (size_t i = 0; i < adjacency_matrix.size(); i++)
{
if (adjacency_matrix.size() != adjacency_matrix[i].size())
{
// If the matrix is not square, it is not a valid adjacency matrix
throw std::invalid_argument("The matrix is not square");
}
for (size_t j = 0; j < adjacency_matrix[i].size(); j++)
{
if (adjacency_matrix[i][j] != adjacency_matrix[j][i])
{
// If the matrix is not symmetric, the graph is directed
isDirected = true;
}
if (adjacency_matrix[j][j] != 0)
{
// If the diagonal is not zero, the matrix is not a valid adjacency matrix
throw std::invalid_argument("The matrix is not a valid adjacency matrix");
}
if (adjacency_matrix[i][j] != 0)
{
// If the matrix has a non-zero element, it is an edge
numOfEdges++;
}
if (adjacency_matrix[i][j] < 0){
// If the matrix has a negative element, the graph has a negative edge
hasNegativeEdge = true;
}
if (adjacency_matrix[i][j] != 1 && adjacency_matrix[i][j] != 0){
// If the matrix has a non-zero element greater than 1, the graph has a weighted edge
withWeights = true;
}
}
}
if (!isDirected)
{
numOfEdges = numOfEdges / 2;
}
this->matrix = adjacency_matrix;
}
// Method to print the graph
void Graph::printGraph()
{
std::cout << "Graph with " << matrix.size() << " vertices and "<< numOfEdges <<" edges." << std::endl;
for (size_t i = 0; i < matrix.size(); i++)
{
for (size_t j = 0; j < matrix[i].size(); j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
// Method to get the adjacency matrix
std::vector<std::vector<int>> Graph::getMatrix()
{
return matrix;
}
// Method to get if the graph is directed
bool Graph::getIsDirected()
{
return isDirected;
}
// Method to get the number of edges
int Graph::getNumOfEdges()
{
return numOfEdges;
}
// Method to get if the graph has a negative edge
bool Graph::getHasNegativeEdge()
{
return hasNegativeEdge;
}
// Method to get if the graph has a weighted edge
bool Graph::getWithWeights()
{
return withWeights;
}