ADS UNIT - III GRAPHS Part1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

ADVANCED DATA STRUCTURES UNIT - III IT

GRAPHS
In this chapter, we turn our attention to a data structure – Graphs - that differs from all of
the other in one major concept: each node may have multiple predecessors as well as
multiple successors.

Graphs are very useful structures. They can be used to solve complex routing problems,
such as designing and routing airlines among the airports they serve. Similarly, they can be
used to route messages over a computer network from one node to another.

Basic Concepts:
A graph is a collection of nodes, called vertices and a collection of segments called lines
connecting pair of vertices. In other words a graph consists of two sets, a set of vertices and
set of lines.

Graphs may be either directed or undirected.

➢ A directed graph or digraph is a graph in which each line has a direction (arrow
head) to its successor. The line in a directed graph is known as arc. The flow along
the arc between two vertices can follow only the in directed direction.

➢ An undirected graph is a graph in which there is no direction (arrow head) on any of


the lines, which are known as edges. The flow between two vertices can go in either
direction.

A path is a sequence of vertices in which each vertex is adjacent to the next one.

For example: {A, B, C, E} is a one path and {A, B, E, F} is another.

NOTE: Both directed and undirected graphs have paths.

PVPSIT Page 1
ADVANCED DATA STRUCTURES UNIT - III IT

Two vertices in a graph are said to be adjacent vertices (or neighbors) if there is a path of
length 1 connecting them.

Consider the above diagrams

In directed graph, B is adjacent to A, where as E is not adjacent to D; but D is adjacent to E.

In undirected graph, E and D are adjacent, but D and F are not.

A cycle is a path, it start with vertex and ends with same vertex.

Example:

A-B-C-A is a cycle

A loop is a special case of cycle in which a single arc begins and ends with the same vertex.
In a loop the end points of the line are the same.

Two vertices are said to be connected if there is a path between them. A graph is said to be
connected if, ignoring direction, there is a path from any vertex to any other vertex.

A directed graph is strongly connected if there is a path from each vertex to every other
vertex in the digraph.

A directed graph is weakly connected if at least two vertices are connected (A connected
undirected graph would always be strongly connected, so the concept is not normally used
with undirected graphs)

PVPSIT Page 2
ADVANCED DATA STRUCTURES UNIT - III IT

A graph is a disjoint graph if it is not connected

The degree of a vertex is the no/of lines incident to it

The out - degree of a vertex in a digraph is the no. of arcs leaving the vertex

The in - degree is the no. of arcs entering the vertex

For example: for vertex B; degree = 3, in - degree = 1, out - degree = 2

NOTE: A tree is a graph in which each vertex has only one predecessor; how ever a graph is
not a tree.

Operations on Graphs:
There are six primitive graph operations that provide the basic modules needed to maintain
a graph. They are

1. Insert a vertex
2. Delete a vertex
3. Add an edge
4. Delete an edge
5. Find a vertex
6. Traverse a graph

Vertex insertion:

Insert vertex adds a new vertex to a graph

When a vertex is inserted it is disjoint; it is not connected to any other vertices in the list

After inserting a vertex it must be connected

The below diagram shows a graph before and after a new vertex is added

PVPSIT Page 3
ADVANCED DATA STRUCTURES UNIT - III IT

Algorithm:

Algorithm insert vertex (graph, data)


Allocate memory for new vertex
Store data in new vertex
Increment graph count
if (empty graph)
Set graph first to new node
else
Search for insertion point
if (inserting before first vertex)
Set graph first to new vertex
else
Insert new vertex in sequence
end if
end insert vertex

Vertex deletion:

Delete vertex removes a vertex from the graph when a vertex is deleted; all connecting
edges are also removed

PVPSIT Page 4
ADVANCED DATA STRUCTURES UNIT - III IT

Algorithm:

Algorithm delete vertex(graph, key)

Return +1 if successful
-1 if degree not zero
-2 if key is not found
if (empty graph)
return -2;
end if
search for vertex to be deleted
if (not found)
return -2;
end if
if ( vertex indegree > 0 or indegree > 0)
return -1;
end if
delete vertex
decrement graph count
return 1;
end delete vertex

Edge addition:

Add edge connects a vertex to destination vertex. If a vertex requires multiple edges, add
an edge must be called once for each adjacent vertex. To add an edge, two vertices must be
specified. If the graph is a digraph, one of the vertices must be specified as the source and
one as the destination.

The below diagram shows adding an edge {A, E} to the graph

PVPSIT Page 5
ADVANCED DATA STRUCTURES UNIT - III IT

Algorithm:

Algorithm insertArc (graph, fromkey, tokey)

Return +1 if successful
-2 if fromkey not found
-3 if tokey not found
Allocate memory for new arc
Search and set fromvertex
if (fromvertex not found)
return -2;
end if
search and set tovertex
if (tovertex not found)
return -3;
end if
increment fromvertex outdegree
increment tovertex indegree
set arc destination to tovertex
if ( fromvertex arc list empty)
set fromvertex firstArc to new arc
set new arc nextArc to null
return 1;
end if
find insertion point in arc list
if (insert at beginning of arc list)
set fromvertex firstArc to new arc
else
insert in arc list
end if
return 1;
end insertArc

PVPSIT Page 6
ADVANCED DATA STRUCTURES UNIT - III IT

Edge deletion:

Delete edge removes one edge from a graph.

Below diagram shows that deleted the edge {B, E} from the graph

Algorithm:

Algorithm deleteArc(graph, fromkey, tokey)

Return +1 if successful
-2 if fromkey not found
-3 if tokey not found
if (empty graph)
return -2;
end if
search and set fromvertex to tovertex with key equal to fromkey
if (fromvertex arc not found)
return -2;
end if
if (fromvertex arc list null)
return -3;
end if
search and find arc with key equal to tokey
if (tokey not found)
return -3;
enf if
set tovertex to arc destination
delete arc
decrement fromvertex outdegree
decrement tovertex indegree
return 1;
end deleteArc

PVPSIT Page 7
ADVANCED DATA STRUCTURES UNIT - III IT

Find vertex:

Find vertex traverse a graph, looking for a specified vertex. If the vertex is found its data are
returned and if it is not found then an error is indicated.

The below figure shows find vertex traverses the graph, looking for vertex C

Algorithm:

Algorithm retrievevertex (graph, key, dataout)


Return +1 if successful
-2 if key not found
if (empty graph)
return -2;
end if
search for vertex
if (vertex found)
move locptr data to dataout
return 1;
else
return -2;
end if
end retrievevertex

PVPSIT Page 8
ADVANCED DATA STRUCTURES UNIT - III IT

Graph Storage Structure:


To represent a graph, we need to store two sets. The first set represents the vertices of the
graph and the second set represents the edges or arcs. The two most common structures
used to store these sets are arrays and linked lists. Although the arrays offer some simplicity
this is a major limitation.

Adjacency Matrix:

The adjacency matrix uses a vector (one – dimensional array) for the vertices and a matrix
(two – dimensional array) to store the edges. If two vertices are adjacent – that is if there is
no edge between them, intersect is set to 0.

If the graph is directed, the intersection in the adjacency matrix indicates the direction

In the below diagram, there is an arc from sources vertex B to destination vertex C. In the
adjacency matrix, this arc is seen as a 1 in the intersection from B (on the left) to C (on the
top). Because there is no arc from C to B, however, the intersection from C to B is 0.

PVPSIT Page 9
ADVANCED DATA STRUCTURES UNIT - III IT

NOTE: In adjacency matrix representation, we use a vector to store the vertices and a matrix
to store the edges.

In addition to the limitation that the size of graph must be know before the program starts,
there is another serious limitation in the adjacency matrix: only one edge can be stored
between any two vertices. Although this limitation does not prevent many graphs from
using the matrix format, some network structures require multiple lines between vertices.

Adjacency list:

The adjacency list uses a two – dimensional ragged array to store the edges. An adjacency
list is shown below.

The vertex list is a singly linked list of vertices in the list. Depending on the application, it
could also be implemented using doubly linked lists or circularly linked lists. The pointer at
the left of the list links the vertex entries. The pointer at the right in the vertex is a head
pointer to a linked list of edges from the vertex. Thus, in the non – directed graph on the left
in above figure there is a path from vertex B to vertices A, C, and E. To find these edges in
the adjacency list, we start at B’s vertex list entry and traverse the linked list to A, then to C,
and finally to E.

NOTE: In the adjacency list, we use a linked list to store the vertices and a two – dimensional
linked list to store the arcs.

PVPSIT Page 10
ADVANCED DATA STRUCTURES UNIT - III IT

Traverse graph:
There is always at least one application that requires that all vertices in a given graph be
visited; as we traverse the graph, we set the visited flag to on to indicate that the data have
been processed

That is traversal of a graph means visiting each of its nodes exactly once. This is
accomplished by visiting the nodes in a systematic manner

There are two standard graph traversals: depth first and breadth first. Both use visited flag

Depth – First Traversal:

In the depth – first traversal, we process all of a vertex’s descendants before we move to an
adjacent vertex. This concept is most easily seen when the graph is a tree

In the below figure we show the tree pre – order traversal processing sequence, one of the
standard depth – first traversals

In a similar manner, the depth – first traversal of a graph starts by processing the first
vertex; we select any vertex adjacent to the first vertex and process it. This continues until
we found no adjacent entries

This is similar to reaching a leaf in a tree. We require a stack to complete the traversal
i.e. last – in – first – out (LIFO) order

Let’s trace a depth – first traversal through the graph in below figure the numbering in the
box next to a vertex indicates the processing order

Trace of the DFS:

1. We begin by pushing the first vertex, into the stack

PVPSIT Page 11
ADVANCED DATA STRUCTURES UNIT - III IT

2. We then loop, pop the stack and after processing the vertex, push all of the adjacent
vertices into the stack

3. When the stack is empty traversal is completed

NOTE: In the depth – first traversal, all of a node’s descendents are processed before
moving to an adjacent node

Consider the above graph, let node A be the starting vertex

1. Begin with node A push onto stack

2. While stack not equal to empty

Pop A; state A is visited

Push nodes adjacent to A to stack and make their state waiting

3. Pop X; state B is visited

Push nodes adjacent to X into stack

4. Pop H; state H is visited

Push nodes adjacent to H into stack already G is in waiting state, then push nodes E
and P

5. Pop P; state P is visited


PVPSIT Page 12
ADVANCED DATA STRUCTURES UNIT - III IT

Push nodes adjacent to P are H, G, E; H is already in visited state, G and E are in


waiting state

6. Pop E; state E is visited

Push adjacent nodes, H is already visited, so push Y and M into the stack

7. Pop Y; state Y is visited

Push nodes adjacent to Y into stack, E is visited, M already in waiting state

8. Pop M; state M is visited

Push nodes adjacent to M, which is J

9. Pop J; state J is visited

No nodes are there to be process

10. Pop G; state G is visited

Now the stack is empty

The depth – first order of the visited nodes are A X H P E Y M J G

Breadth – First traversal:

In the breadth – first traversal of a graph, we process all adjacent vertices of a vertex before
going to the next level. We first saw the breadth – first traversal of a tree as shown in below

This traversal starts at level 0 and then processes all the vertices in level 1 before going on
to process the vertices in level 2.

The breadth – first traversal of a graph follows the same concept, begin by picking a starting
vertex A after processing it, process all of its adjacent vertices and continue this process
until get no adjacent vertices

PVPSIT Page 13
ADVANCED DATA STRUCTURES UNIT - III IT

The breadth – first traversal uses a queue rather than a stack. As we process each vertex, we
place all of its adjacent vertices in the queue. Then to select the next vertex to be processed,
we delete a vertex from the queue and process it.

Trace of the BFS:

1. We begin by enqueuing vertex A in the queue

2. We then loop, dequeuing the queue and processing the vertex from the front of
the queue. After processing the vertex, we place all of its adjacent vertices into
the queue. Thus in the above diagram we dequeue vertex X, process it, and then
place vertices G and H in the queue.

3. When the queue is empty, the traversal is complete.

NOTE: In the breadth – first traversal, all adjacent vertices are processed before processing
the descendents of a vertex.

Let’s trace this logic through the graph in below figure:

PVPSIT Page 14
ADVANCED DATA STRUCTURES UNIT - III IT

Algorithms:

Depth – First Search:

Policy: Don’t push nodes twice


// non-recursive, preorder, depth-first search
void dfs (Node v) {
if (v == null)
return;
push(v);
while (stack is not empty) {
pop(v);
if (v has not yet been visited)
mark&visit(v);
for (each w adjacent to v)
if (w has not yet been visited && not yet stacked)
push(w);
} // while
} // dfs

Breadth-First Search:

// non-recursive, preorder, breadth-first search


void bfs (Node v) {
if (v == null)
return;
enqueue(v);
while (queue is not empty) {
dequeue(v);
if (v has not yet been visited)
mark&visit(v);
for (each w adjacent to v)
if (w has not yet been visited && has not been queued)
enqueue(w);
} // while
} // bfs

PVPSIT Page 15

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy