Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab Manual 12 DSA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Student Name Fazeel Ahmad

Student Roll #
INFT-18111027

Department
Information Technology

Batch/Year/Section
2018-2022

For Lab. Instructor

Marks Signature

Course: Data Structures & Algorithms

Lab Instructor:
Ms. Humaira Anwer

Department of Computer Science & Information Technology

Khwaja Fareed University of Engineering


& Information Technology,
(KFUEIT)
Abu Dhabi Road,
Rahim Yar Khan.

05/06/2017
Lab Manual Graphs
#12

Lab Manual # 12
Graphs Abstract Data Type

KFUEIT Department of CS/IT


178
Objective
After performing this lab students would be able to:
1. Understand the basics of graph abstract data type.
2. Understand and implement various algorithms for graph.
3. Implement the algorithm for breadth first search and depth first search in graphs.
Graph
Graph is a nonlinear data structure, it contains a set of points known as nodes (or vertices)
and set of links known as edges (or Arcs) which connects the vertices. A graph is defined as
follows:

“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.”

Generally, a graph G is represented as G = ( V , E ), where V is set of vertices and E is set of


edges.

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)).

Edges are two types.

Undirected Edge - An undirected edge is a bidirectional edge. If there is a undirected edge


between vertices A and B then edge (A , B) is equal to edge (B , A).

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

A graph with only undirected edges is said to be undirected graph.

Directed Graph

A graph with only directed edges is said to be directed graph.

Mixed Graph

A graph with undirected and directed edges is said to be mixed graph.

End vertices or Endpoints

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

A directed edge is said to be outgoing edge on its orign vertex.

Incoming Edge

A directed edge is said to be incoming edge on its destination vertex.

Degree

Total number of edges connected to a vertex is said to be degree of that vertex.

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).

Parallel edges or Multiple edges


If there are two undirected edges to have the same end vertices, and for two directed edges to
have the same origin and the same destination. Such edges are called parallel edges or
multiple edges.
Simple Graph

A graph is said to be simple if there are no parallel and self-loop edges.

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

A vertex with degree zero is called an 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.

Applications of Graph Theory

Graph theory has its applications in diverse fields of engineering −

 Electrical Engineering − The concepts of graph theory is used extensively in


designing circuit connections. The types or organization of connections are named as
topologies. Some examples for topologies are star, bridge, series, and parallel
topologies.
 Computer Science − Graph theory is used for the study of algorithms. For example,
i. Kruskal's Algorithm
ii. Prim's Algorithm
iii. Dijkstra's Algorithm
 Computer Network − The relationships among interconnected computers in the
network follows the principles of graph theory.
 Science − The molecular structure and chemical structure of a substance, the DNA
structure of an organism, etc., are represented by graphs.
 Linguistics − The parsing tree of a language and grammar of a language uses graphs.
 General − Routes between the cities can be represented using graphs. Depicting
hierarchical ordered information such as family tree can be used as a special type of
graph called tree.

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.

For example, consider the following undirected graph representation:


1. Give in degree and out degree of above graph

Vertices Indegree Outdegree

b
c

d
e
f
g

2. Draw adjacency matrix for above graph


3. Give degree sequence for above graph for vertices {a, b, c, d, e, f}

Vertex

Connecting to

Degree

Depth First Search


Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack
to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

It employs the following rules:

 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.

Breadth First Search


Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a
queue to remember to get the next vertex to start a search, when a dead end occurs in any
iteration. It employs the following rules.

 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 −

 Add Vertex − Adds a vertex to the graph.


 Add Edge − Adds an edge between the two vertices of the graph.
 Display Vertex − Displays a vertex of the 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;

Add Vertex Algorithm

void addVertex (char label)

Description: This algorithm adds new vertex to the graph

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

void addEdge (int start, int end)

Description: This algorithm adds new edge to the graph

1. START
2. SET adjMatrix[start][end] = 1;
3. SET adjMatrix[end][start] = 1;
4. END

DISPLAY VERTEX

void DisplayVertex (int vertexIndex)

Description: This algorithm displays vertex of graph


1. START
2. PRINT lstVertices[vertexIndex]->label)
3. END

ADJACENT UNVISITED 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

DEPTH FIRST SEARCH

void depthFirstSearch()
1. START
2. DECLARE int i

//mark first node as visited


3. SET lstVertices[0]->visited = true

//display the vertex


4. CALL displayVertex(0)

//push vertex index in stack


5. push(0);

6. while(!isStackEmpty())
//get the unvisited vertex of vertex which is at top of the stack
a. int unvisitedVertex = getAdjUnvisitedVertex(peek());

//no adjacent vertex found


b. if(unvisitedVertex == -1)
c. pop();
d. else
e. lstVertices[unvisitedVertex]->visited = true
f. displayVertex(unvisitedVertex)
g. push(unvisitedVertex)
h. end else
7. end while
8. //stack is empty, search is complete, reset the visited flag
9. for(i = 0;i < vertexCount;i++)
10. lstVertices[i]->visited = false
11. End for
12. END

BREADTH FIRST SEARCH

void breadthFirstSearch()
1. START
2. DECLARE int i

//mark first node as visited


3. SET lstVertices[0]->visited = true

//display the vertex


4. CALL displayVertex(0)

//insert vertex index in queue


5. CALL insert(0)
6. int unvisitedVertex;

7. while(!isQueueEmpty())
//get the unvisited vertex of vertex which is at front of the queue
8. int tempVertex = removeData()

//no adjacent vertex found


9. while((unvisitedVertex = getAdjUnvisited Vertex(tempVertex)) != -1)
10. lstVertices[unvisitedVertex]->visited = true;
11. displayVertex(unvisitedVertex);
12. insert(unvisitedVertex);
13. END loop step 9
14. END loop step 7

//queue is empty, search is complete, reset the visited flag


15. for(i = 0;i<vertexCount;i++)
16. lstVertices[i]->visited = false;
17. End for
18. END
LAB TASK 01

1. Write a single C++ code to implement Graph Data structure

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;
}

You might also like