-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.cpp
More file actions
116 lines (91 loc) · 2.06 KB
/
Graph.cpp
File metadata and controls
116 lines (91 loc) · 2.06 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
113
114
115
116
/* An implementation of an undirected graph using adjacency lists
* Code by: Humayun Kabir, humayun.k1@gmail.com */
#include <iostream>
#include <fstream>
#include "linkedList.cpp"
class Graph {
private:
//Number of vertices in the graph
int n;
//Adjacency list of each vertex
LinkedList<int> *adj;
public:
//Constructor
Graph(int n) : n(n) {
adj = new LinkedList<int>[n];
}
//Makes a graph from an input file
//First line contains n m (number vertices and number edges)
//each line contains an edge: i j (i is connected to j)
Graph(char *fileName) {
ifstream fileHandle(fileName);
if( fileHandle.is_open() ) {
int value, numToken = 0;
int i, j;
while( fileHandle >> value ) {
numToken++;
if( numToken == 1 ) {
n = value;
adj = new LinkedList<int>[n];
}
else if(numToken == 2) {
cout<<"Number of Edges: "<<value<<endl;
}
else {
if( numToken % 2 == 1)
i = value - 1;
else {
j = value - 1;
adj[i].add(j);
adj[j].add(i);
}
}
}
fileHandle.close();
}
else
cout<<"File could not be opened\n";
}
//add edge (v,w)
void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v);
}
//returns adjacency of a vertex v
LinkedList<int> & adjList(int v) {
return adj[v];
}
//returns number of vertices in the graph
int N() {
return n;
}
//returns number of edges in the graph
int M() {
int numEdges = 0;
for(int v = 0; v < n; v++)
numEdges += adj[v].size();
return numEdges/2;
}
//returns degree of a vertex
int degree(int v) {
return adj[v].size();
}
//Destructor
~Graph() {
delete [] adj;
}
};
/*
//test the graph
int main() {
Graph g("graph2.txt");
cout<<"Number of vertices: "<<g.N() <<endl;
cout<<"Number of edges: "<<g.M() <<endl;
int vertex = 0;
cout<<"Degree of vertex "<< vertex<< " is: "<< g.degree(vertex) << endl;
cout<<"Adjacency list of "<< vertex <<": \n";
for(LinkedList<int>::iterator it = g.adjList(0).begin(); it != g.adjList(0).end(); it++) {
cout<<*it<<endl;
}
return 0;
} */