-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.cpp
130 lines (118 loc) · 2.52 KB
/
Graph.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
119
120
121
122
123
124
125
126
127
128
129
130
#include "Graph.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <fstream>
#include <string>
#include <utility>
using namespace std;
Graph::Graph()
{
vertex = 0;
edge = 0;
neighbourList = nullptr;
}
Graph::~Graph()
{
if(!neighbourList)
delete [] neighbourList;
}
void Graph::inputGraphConsole(void)
{
cin >> vertex;
neighbourList = new vector<unsigned int>[vertex];
unsigned int v1, v2;
edge = 0;
while(cin >> v1 >> v2)
{
neighbourList[v1].push_back(v2);
neighbourList[v2].push_back(v1);
edgesList.push_back(make_pair(v1,v2));
edge++;
}
cin.clear();
}
bool Graph::inputGraphFile(std::string filename)
{
fstream file;
file.open(filename, ios::in);
if(!file.good())
return false;
file >> vertex;
neighbourList = new vector<unsigned int>[vertex];
unsigned int v1, v2;
edge = 0;
while(file.good())
{
file >> v1 >> v2;
if(file.fail())
break;
neighbourList[v1].push_back(v2);
neighbourList[v2].push_back(v1);
edgesList.push_back(make_pair(v1,v2));
edge++;
}
file.close();
return true;
}
int Graph::getQuantityOfComponents(unsigned int V1, unsigned int V2)
{
int cn = 0;
unsigned int v, u;
bool visited[vertex];
stack<unsigned> stc;
for (auto i = 0; i < vertex; ++i)
visited[i] = false;
visited[V1] = true;
visited[V2] = true;
for (unsigned i = 0; i < vertex; ++i)
{
if (!visited[i])
{
cn++;
if (cn > 1)
return cn;
stc.push(i);
visited[i] = true;
while (!stc.empty())
{
v = stc.top();
stc.pop();
for (auto it = neighbourList[v].begin(); it != neighbourList[v].end(); ++it)
{
u = *it;
if (!visited[u])
{
stc.push(u);
visited[u] = true;
}
}
}
}
}
return cn;
}
std::vector<std::pair<unsigned int, unsigned int>> Graph::getBridges()
{
unsigned V1, V2, cn;
std::vector<std::pair<unsigned int, unsigned int>> bridgeEdes;
for (auto i = 0; i < edgesList.size(); ++i)
{
V1 = edgesList[i].first;
V2 = edgesList[i].second;
cn = getQuantityOfComponents(V1, V2);
if(cn>1)
bridgeEdes.push_back(make_pair(V1, V2));
}
return bridgeEdes;
}
void Graph::printGraph()
{
cout << "Vertex: " << vertex << "\tEdge: " << edge;
cout << "\nEdges:\n";
for(auto i = 0; i < edgesList.size(); i++)
{
cout << edgesList[i].first << " " << edgesList[i].second << endl;
}
}