Professional Documents
Culture Documents
DATA STRUCTURES
AND
ALGORITHMS
Lecture Notes 12
Graphs
Spring 2008
A B
D E C
D E C
The numbering of the vertices, and their physical arrangement are not important.
180
Indianapolis Columbus
180
Indianapolis Columbus
180
Indianapolis Columbus
0 7 8
6
1 2
9 10
3
4
5 11 12
public:
// Constructor
/** Construct a graph
@param n The number of vertices
@param d True if this is a directed graph
*/
Graph(int n, bool d) : num_v(n), directed(d) {}
// Virtual Destructor
virtual ~Graph() {}
protected:
// Data fields
/** The number of vertices */
int num_v;
/** Flag to indicate whether this is a directed graph */
bool directed;
Function Behavior
bool operator==(const Edge& other) Compare two Edges for equality. Edges
are equal if their source and destination
are equal. The weight is not considered.
bool operator!=(const Edge& other) The negation of the equality operator.
int get_dest() const Returns the destination vertex.
int get_source() const Returns the source vertex.
double get_weight() const Returns the weight.
string to_string() const Returns a string representation of the
edge.
ostream& operator<<(ostream&, Overloaded ostream insertion operator.
const Edge&)
0 1
0 1 2 3 4
0 1.0 1.0
2 1 1.0 1.0 1.0 1.0
2 1.0 1.0
3 1.0 1.0 1.0
4 3 4 1.0 1.0 1.0
0 1 2 0 1 2 3 4 5
0 1.0 1.0
1 1.0
2 1.0 1.0
3 1.0
4 1.0
3 4 5 5 1.0
public:
Edge operator*() { return ptr_to_impl->operator*(); }
iterator& operator++() { ++(*ptr_to_impl); return *this; }
iterator operator++(int)
{ iterator temp(*this); ++(*ptr_to_impl); return temp;}
bool operator==(const iterator& other) const
{ return *ptr_to_impl == *other.ptr_to_impl; }
bool operator!=(const iterator& other) const
{ return !((*this) == other); }
~iterator() {delete ptr_to_impl;}
iterator(const iterator& other) :
ptr_to_impl(other.ptr_to_impl->clone()) {}
iterator(iter_impl* p_impl) : ptr_to_impl(p_impl) {}
private:
/** Pointer to the implementation */
iter_impl* ptr_to_impl;
}; // End iterator
public:
Edge operator*() {
return *current;
}
Graph::iter_impl& operator++() {
++current;
return *this;
}
Graph::iter_impl* clone() {
return new iter_impl(current);
}
GIT – Computer Engineering Department 39
The List_Graph::iter_impl class (2)
private:
// Data fields
}; // End iter_impl
0 4
3 1 6
2 7
9 8
vector<int> parent
[0] -1
[1] 0
[2] 1
[3] 0
[4] 1
[5] 4
[6] 1
[7] 1
[8] 2
[9] 2
3
8
4 5 6 7
11
10
12
2 4
8 7 5
12 11 6 9 3 10
3
8
4 5 6 7
11
10
12
1 2
3 4 5 6
∑c
i =1
i ,i +1
1
100
10
2 5
30
50
10
60
20
3 4
Example :
Assume that start node s is v1
First vertex selected is v1 Initial configuration of
– with path length 0 vectors in Dijkstra’s
This vertex is marked known Algorithm
Number of edges in
minimum spanning tree
is |V| -1