-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathGraph.cpp
81 lines (65 loc) · 1.42 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
#include "Graph.h"
Graph::Graph(int n, const list< pair<int, int> > & edges):
n(n),
m(edges.size()),
adjMat(n, vector<bool>(n, false)),
adjList(n),
edges(),
edgeIndex(n, vector<int>(n, -1))
{
for(list< pair<int, int> >::const_iterator it = edges.begin(); it != edges.end(); it++)
{
int u = (*it).first;
int v = (*it).second;
AddEdge(u, v);
}
}
pair<int, int> Graph::GetEdge(int e) const
{
if(e > (int)edges.size())
throw "Error: edge does not exist";
return edges[e];
}
int Graph::GetEdgeIndex(int u, int v) const
{
if( u > n or
v > n )
throw "Error: vertex does not exist";
if(edgeIndex[u][v] == -1)
throw "Error: edge does not exist";
return edgeIndex[u][v];
}
void Graph::AddVertex()
{
for(int i = 0; i < n; i++)
{
adjMat[i].push_back(false);
edgeIndex[i].push_back(-1);
}
n++;
adjMat.push_back( vector<bool>(n, false) );
edgeIndex.push_back( vector<int>(n, -1) );
adjList.push_back( list<int>() );
}
void Graph::AddEdge(int u, int v)
{
if( u > n or
v > n )
throw "Error: vertex does not exist";
if(adjMat[u][v]) return;
adjMat[u][v] = adjMat[v][u] = true;
adjList[u].push_back(v);
adjList[v].push_back(u);
edges.push_back(pair<int, int>(u, v));
edgeIndex[u][v] = edgeIndex[v][u] = m++;
}
const list<int> & Graph::AdjList(int v) const
{
if(v > n)
throw "Error: vertex does not exist";
return adjList[v];
}
const vector< vector<bool> > & Graph::AdjMat() const
{
return adjMat;
}