Lab Manual 12 DSA
Lab Manual 12 DSA
Lab Manual 12 DSA
Student Roll #
INFT-18111027
Department
Information Technology
Batch/Year/Section
2018-2022
Marks Signature
Lab Instructor:
Ms. Humaira Anwer
05/06/2017
Lab Manual Graphs
#12
Lab Manual # 12
Graphs Abstract Data Type
“Graph is a collection of vertices and arcs which connects vertices in the graph.”
“Graph is a collection of nodes and edges which connects nodes in the graph.”
Example
The following is a graph with 5 vertices and 6 edges. This graph G can be defined as G = ( V
, E ) Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}.
Graph Terminology
We use the following terms in graph data structure...
Vertex
An individual data element of a graph is called as Vertex. Vertex is also known as node.
In above example graph, A, B, C, D & E are known as vertices.
Edge
An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is
represented as (startingVertex, endingVertex). For example, in above graph, the link between
vertices A and B is represented as (A,B). In above example graph, there are 7 edges (i.e.,
(A,B), (A,C), (A,D), (B,D), (B,E), (C,D), (D,E)).
Directed Edge - A directed edge is a unidirectional edge. If there is a directed edge between
vertices A and B then edge (A , B) is not equal to edge (B , A).
Undirected Graph
Directed Graph
Mixed Graph
The two vertices joined by an edge are called the end vertices (or endpoints) of the edge.
Adjacent
If there is an edge between vertices A and B then both A and B are said to be adjacent. In
other words, Two vertices A and B are said to be adjacent if there is an edge whose end
vertices are A and B.
Outgoing Edge
Incoming Edge
Degree
Indegree
Total number of incoming edges connected to a vertex is said to be indegree of that vertex.
Or Indegree of vertex V is the number of edges which are coming into the vertex V.
Notation − deg+(V).
Outdegree
Total number of outgoing edges connected to a vertex is said to be outdegree of that vertex.
Or Outdegree of vertex V is the number of edges which are going out from the vertex V.
Notation − deg-(V).
Path
A path is a sequence of alternating vertices and edges that starts at a vertex and ends at a
vertex such that each edge is incident to its predecessor and successor vertex.
Pendent Vertex
By using degree of a vertex, we have two special types of vertices. A vertex with degree one
is called a pendent vertex.
Example
Here, in this example, vertex ‘a’ and vertex ‘b’ have a connected edge ‘ab’. So with respect to
the vertex ‘a’, there is only one edge towards vertex ‘b’ and similarly with respect to the
vertex ‘b’, there is only one edge towards vertex ‘a’. Final y, vertex ‘a’ and vertex ‘b’ has
degree as one which are also called as the pendent vertex.
Isolated Vertex
Example
Here, the vertex ‘a’ and vertex ‘b’ has a no connectivity between each other and also to any
other vertices. So the degree of both the vertices ‘a’ and ‘b’ are zero. These are also cal ed as
isolated vertices.
Adjacency Matrix
In this representation, graph can be represented using a matrix of size total number of vertices
by total number of vertices. That means if a graph with 4 vertices can be represented using a
matrix of 4X4 class. In this matrix, rows and columns both represents vertices. This matrix is
filled with either 1 or 0. Here, 1 represents there is an edge from row vertex to column vertex
and 0 represents there is no edge from row vertex to column vertex.
b
c
d
e
f
g
Vertex
Connecting to
Degree
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a
stack.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It wil pop up
all the vertices from the stack, which do not have adjacent vertices.)
Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a
queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
Basic Operations
Following are basic primary operations of a Graph −
Vertex in Graph
struct Vertex
{
char label;
bool visited;
};
Vertex *vertex;
struct Vertex* lstVertices[MAX]; //array of vertices
//array of vertices
struct Vertex* lstVertices[MAX];
//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;
//stack functions
void push(int item) {
stack[++top] = item;
}
int pop() {
return stack[top--];
}
int peek() {
return stack[top];
}
bool isStackEmpty() {
return top == -1;
}
//queue functions
void insert(int data) {
queue[++rear] = data;
queueItemCount++;
}
int removeData() {
queueItemCount--;
return queue[front+
+];
}
bool isQueueEmpty() {
return queueItemCount == 0;
1. START
2. SET vertex=new Vertex
3. SET vertex->label=label
4. SET vertex->visited=false
5. SET lstVertices[vertexCount++] = vertex;
6. EXIT
ADD EDGE
1. START
2. SET adjMatrix[start][end] = 1;
3. SET adjMatrix[end][start] = 1;
4. END
DISPLAY VERTEX
int getAdjUnvisitedVertex(int
vertexIndex)
1. START
2. int i;
3. for(i = 0; i<vertexCount; i++)
4. {
5. if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false)
6. return i
7. }
8.
return
9.
10. } -1;
11. END
void depthFirstSearch()
1. START
2. DECLARE int i
6. while(!isStackEmpty())
//get the unvisited vertex of vertex which is at top of the stack
a. int unvisitedVertex = getAdjUnvisitedVertex(peek());
void breadthFirstSearch()
1. START
2. DECLARE int i
7. while(!isQueueEmpty())
//get the unvisited vertex of vertex which is at front of the queue
8. int tempVertex = removeData()
Code Area
#include <iostream>
using namespace std;
// stores adjacency list items
struct adjNode {
int val, cost;
adjNode* next;
};
// structure to store edges
struct graphEdge {
int start_ver, end_ver, weight;
};
class DiaGraph{
// insert new nodes into adjacency list from given graph
adjNode* getAdjListNode(int value, int weight, adjNode* head) {
adjNode* newNode = new adjNode;
newNode->val = value;
newNode->cost = weight;
newNode->next = head; // point new node to current head
return newNode;
}
int N; // number of nodes in the graph
public:
adjNode **head; //adjacency list as array of pointers
// Constructor
DiaGraph(graphEdge edges[], int n, int N) {
// allocate new node
head = new adjNode*[N]();
this->N = N;
// initialize head pointer for all vertices
for (int i = 0; i < N; ++i)
head[i] = nullptr;
// construct directed graph by adding edges to it
for (unsigned i = 0; i < n; i++) {
int start_ver = edges[i].start_ver;
int end_ver = edges[i].end_ver;
int weight = edges[i].weight;
// insert in the beginning
adjNode* newNode = getAdjListNode(end_ver, weight,
head[start_ver]);
// point head pointer to new node
head[start_ver] = newNode;
}
}
// Destructor
~DiaGraph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
// print all adjacent vertices of given vertex
void display_AdjList(adjNode* ptr, int i)
{
while (ptr != nullptr) {
cout << "(" << i << ", " << ptr->val
<< ", " << ptr->cost << ") ";
ptr = ptr->next;
}
cout << endl;
}
// graph implementation
int main()
{
// graph edges array.
graphEdge edges[] = {
// (x, y, w) -> edge from x to y with weight w
{0,1,2},{0,2,4},{1,4,3},{2,3,2},{3,1,4},{4,3,3}
};
int N = 6; // Number of vertices in the graph
// calculate number of edges
int n = sizeof(edges)/sizeof(edges[0]);
// construct graph
DiaGraph diagraph(edges, n, N);
// print adjacency list representation of graph
cout<<"Graph adjacency list "<<endl<<"(start_vertex, end_vertex,
weight):"<<endl;
for (int i = 0; i < N; i++)
{
// display adjacent vertices of vertex i
display_AdjList(diagraph.head[i], i);
}
return 0;
}