0% found this document useful (0 votes)
23 views

Graph

A graph G is composed of vertices V connected by edges E. An edge is an ordered or unordered pair of vertices. Graphs can model networks and are represented using adjacency matrices or lists. Adjacency matrices store whether an edge exists between two vertices in a 2D array while adjacency lists store the neighbors of each vertex in a linked list. Graphs have applications in modeling networks and analyzing connectivity between components.

Uploaded by

Avinash Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Graph

A graph G is composed of vertices V connected by edges E. An edge is an ordered or unordered pair of vertices. Graphs can model networks and are represented using adjacency matrices or lists. Adjacency matrices store whether an edge exists between two vertices in a 2D array while adjacency lists store the neighbors of each vertex in a linked list. Graphs have applications in modeling networks and analyzing connectivity between components.

Uploaded by

Avinash Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Graph

What is a Graph?
• A graph G = (V,E) is composed of:
V: set of vertices
E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:
a b V= {a,b,c,d,e}

E= {(a,b),(a,c),(a,d),
c (b,e),(c,d),(c,e),
(d,e)}

d e
Applications
CS16
• electronic circuits

• networks (roads, flights, communications)

JFK

LAX STL
HNL
DFW
FTL
Terminology:
Adjacent and Incident
• If (v0, v1) is an edge in an undirected graph,
– v0 and v1 are adjacent
– The edge (v0, v1) is incident on vertices v0 and v1

• If <v0, v1> is an edge in a directed graph


– v0 is adjacent to v1, and v1 is adjacent from v0
– The edge <v0, v1> is incident on v0 and v1
Terminology: Degree of a Vertex
The degree of a vertex is the number of edges
incident to that vertex
For directed graph,
the in-degree of a vertex v is the number of edges
that have v as the head
the out-degree of a vertex v is the number of edges
that have v as the tail
if di is the degree of a vertex i in a graph G with n vertices and e edges, the
number of edges is

n -1 Why? Since adjacent vertices each


e = (å di ) / 2 count the adjoining edge, it will be
0 counted twice
Examples 0
3 2
1 2
0
3 3

3 1 2 3 3 4 5 6
1 1 1
3 1

3 G2
G1 0 in:1, out: 1

directed graph
1 in: 1, out: 2
in-degree
out-degree

2 in: 1, out: 0

G3
Terminology:
Path
Path: 3 2

sequence of vertices v1,v2,. . .vk


3
such that consecutive vertices vi
and vi+1 are adjacent. 3 3

a b a b

c c

d e d e
abedc bedc
7
More Terminology
• simple path: no repeated vertices
a b

bec
c

d e
• cycle: simple path, except that the last vertex is the same as the first
vertex
a b

acda
c

d e
Even More Terminology
•connected graph: any two vertices are connected by some path

connected not connected

• subgraph: subset of vertices and edges forming a graph


• connected component: maximal connected subgraph. E.g., the
graph below has 3 connected components.
Subgraphs Examples
0 0 1 2 0
0
1 2 3 1 2
1 2
3
3
G1 (i) (ii) (iii) (iv)
(a) Some of the subgraph of G1

0 0 0 0 0

1 1 1
1
2 2
2 (i) (ii) (iii) (iv)
G3 (b) Some of the subgraph of G3
More…
• tree - connected graph without cycles

• forest - collection of trees


tree

tree

forest

tree

tree
Connectivity
• Let n = #vertices, and m = #edges

• A complete graph: one in which all pairs of vertices are


adjacent

• How many total edges in a complete graph?


– Each of the n vertices is incident to n-1 edges, however, we would
have counted each edge twice! Therefore, intuitively, m = n(n -1)/2.

• Therefore, if a graph is not complete, m < n(n -1)/2

n=5
m = (5 * 4)/2 = 10
More Connectivity

n = #vertices n=5
m = #edges
m=4
• For a tree m = n - 1

If m < n - 1, G is not connected

n=5
m=3
Oriented (Directed) Graph

• A graph where edges are directed


Directed vs. Undirected Graph

• An undirected graph is one in which the pair of


vertices in a edge is unordered, (v0, v1) = (v1,v0)

• A directed graph is one in which each edge is a


directed pair of vertices, <v0, v1> != <v1,v0>

tail head
ADT for Graph
objects: a nonempty set of vertices and a set of undirected edges, where each
edge is a pair of vertices

functions: for all graph Î Graph, v, v1 and v2 Î Vertices

Graph Create()::=return an empty graph


Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no
incident edge.
Graph InsertEdge(graph, v1,v2)::= return a graph with new edge
between v1 and v2
Graph DeleteVertex(graph, v)::= return a graph in which v and all edges
incident to it are removed
Graph DeleteEdge(graph, v1, v2)::=return a graph in which the edge (v1, v2)
is removed
Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE
else return FALSE
List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v
Graph Representations

Adjacency Matrix
Adjacency Lists
Adjacency Matrix

Let G=(V,E) be a graph with n vertices.

The adjacency matrix of G is a two-dimensional


n by n array, say adj_mat

If the edge (vi, vj) is in E(G), adj_mat[i][j]=1


If there is no such edge in E(G), adj_mat[i][j]=0

The adjacency matrix for an undirected graph is symmetric;


the adjacency matrix for a digraph
need not be symmetric
Examples for Adjacency Matrix
0 0 4
0
1 2 2 1 5

3 1 3 6

é0 1 1 1ù
é0 1 0ù 7
ê1 0 1 1 úú 2 ê ú
ê 1 0 1 é0 1 1 0 0 0 0 0ù
ê ú ê1
ê1 1 0 1ú êë0 0 0úû ê 0 0 1 0 0 0 0úú
ê ú ê1 0 0 1 0 0 0 0ú
ë1 1 1 0û
ê ú
G2
G1 ê0 1 1 0 0 0 0 0ú
ê0 0 0 0 0 1 0 0ú
ê ú
ê0 0 0 0 1 0 1 0ú
symmetric ê0 0 0 0 0 1 0 1ú
ê ú
êë0 0 0 0 0 0 1 0úû
G4
Merits of Adjacency Matrix
From the adjacency matrix, to determine the
connection of vertices is easy
n -1

The degree of a vertex is å adj _ mat[i][ j]


j =0

For a digraph (= directed graph), the row sum is the


out_degree, while the column sum is the in_degree

n -1 n -1
ind (vi ) = å A[ j , i ] outd (vi ) = å A[i , j ]
j =0 j =0
Adjacency Lists (data structures)
Each row in adjacency matrix is represented as an adjacency list.

#define MAX_VERTICES 50
typedef struct node *node_pointer;

typedef struct node


{
int vertex;
struct node *link;
};

node_pointer graph[MAX_VERTICES];

int n=0; /* vertices currently in use */


0 0 4

2 1 5
1 2 3 6

3 7

0 1 2 3 0 1 2
1 0 2 3 1 0 3
2 0 1 3 2 0 3
3 0 1 2 3 1 2
G1 0 4 5
5 4 6
0 1 6 5 7
1 0 2 1
7 6
2
G3 G4 An undirected graph with n
2 vertices and e edges ==> n
head nodes and 2e list nodes
Some Operations
!degree of a vertex in an undirected graph
–# of nodes in adjacency list
!out-degree of a vertex in a directed graph
–# of nodes in its adjacency list
!in-degree of a vertex in a directed graph
–traverse the whole data structure.
!# of edges in a graph
–determined in O(n+e)
Graph Traversal Techniques

• The previous connectivity problem, as well as many

other graph problems, can be solved using graph

traversal techniques

• There are two standard graph traversal techniques:

– Depth-First Search (DFS)

– Breadth-First Search (BFS)


Graph Traversal (Contd.)
• In both DFS and BFS, the nodes of the undirected graph are visited

in a systematic manner so that every node is visited exactly one.

• Both BFS and DFS give rise to a tree:

– When a node x is visited, it is labeled as visited, and it is added

to the tree

– If the traversal got to node x from node y, y is viewed as the

parent of x, and x a child of y


Graph Traversal (Contd.)
• During the execution of algorithm, each node of G
will be in one states

– STATUS = 1: Ready State


• The initial state of the Node N

– STATUS = 2: Waiting State


• The Node N is on the Queue of Stack, waiting to be
Processed

– STATUS = 1: Processing State


• The Node N has been Processed
BFS (Breath-First Search)
Algorithm A: This Algorithm executes a BSF on Graph G beginning
at a start node A
1. Initialize all node to the Ready State (STATUS=1)
2. Put the starting node A in Queue and change its status to the
waiting state (STATUS=2)
3. Repeat steps 4 and 5 until QUEUE is empty:
4. Remove the front node N of QUEUE. Process N and change
the Status of N to the Processed state (STATUS=3)
5. Add to the rear of QUEUE all the neighbors of N that are
in the steady state (STATUS=1), and change their status to
the waiting state (STATUS=2).
[End of step 3 loop]
6. Exit
DFS (Depth-First Search)
Algorithm B: This Algorithm executes a DSF on Graph G beginning
at a start node A
1. Initialize all node to the Ready State (STATUS=1)
2. Put the starting node A on to STACK and change its status to
the waiting state (STATUS=2)
3. Repeat steps 4 and 5 until STACK is empty:
4. Pop the top node N of STACK. Process N and change the
Status of N to the Processed state (STATUS=3)
5. Push onto STACK all the neighbors of N that are in the
steady state (STATUS=1), and change their status to the
waiting state (STATUS=2).
[End of step 3 loop]
6. Exit
Depth-First Search
DFS follows the following rules:

1. Select an unvisited node x, visit it, and treat as the


current node

2. Find an unvisited neighbor of the current node, visit it,


and make it the new current node;

3. If the current node has no unvisited neighbors,


backtrack to the its parent, and make that parent the
new current node;

4. Repeat steps 2 and 3 until no more nodes can be visited.

5. If there are still unvisited nodes, repeat from step 1.


Illustration of DFS
0 1
0
2
1
9 4
4
10 5 7
2
11 8
5 9
6
7 11
6 Graph G
8 10

DFS Tree
Implementation of DFS
Observations:

– the last node visited is the first node from which to

proceed.

– Also, the backtracking proceeds on the basis of "last

visited, first to backtrack too".

– This suggests that a stack is the proper data structure to

remember the current node and how to backtrack.


Illustrate DFS with a Stack
• We will redo the DFS on the previous graph, but this
time with stacks
• In Class
DFS (Pseudo Code)
DFS(input: Graph G) {
Stack S; Integer x, t;
while (G has an unvisited node x){
visit(x); push(x, S);
while (S is not empty){
t := peek(S);
if (t has an unvisited neighbor y){
visit(y); push(y, S); }
else
pop(S);
}
}
}
C++ Code for DFS
int * dfs(Graph G){ // returns a parent array representing the DFS tree
int n=G.getNumberOfNodes();
int * parent = new int[n];
Stack S(n); bool visited[n];
for ( int i=0; i<n; i++) visited[i]=false;
int x=0; // begin DFS from node 0
int numOfConnectedComponents=0;
while (x<n){ // begin a new DFS from x
numOfConnectedComponents++;
visited[x]=true; S.push(x); parent[x] = -1; // x is root
while(!S.isEmpty()) // traverse the current piece
// insert here the yellow box from the next slide
x= getNextUnvisited(visited,n,x);
}
cout<<“Graph has “<< numOfConnectedComponents<<
“ connected components\n”;
return p;
}
// Put this before dfs(…)
{
// returns the leftmost unvisited
int t=S.peek( );
// neighbor of node t. If none
int y=getNextUnvisitedNeighbor(
// remains, returns n.
t,G,visited,n);
int getNextUnvisitedNeighbor(int t,
if (y<n){
graph G, bool visited[],int n){
visited[y]=true;
for (int j=0;j<n;j++)
S.push(y);
if (G.isEdge(t,j) && !visited[j])
parent[y]=t;
return j;
}
// if no unvisited neighbors left:
else S.pop( );
return n;
}
}
//Put this before dfs(…). This returns the next unvisited node, or n otherwise
int getNextUnvisited(bool visited[],int n, int lastVisited){
int j=lastVisited+1;
while (visited[j] && j<n) j++;
return j;
}
Breadth-First Search
BFS follows the following rules:

1. Select an unvisited node x, visit it, have it be the root in a

BFS tree being formed. Its level is called the current level.

2. From each node z in the current level, in the order in

which the level nodes were visited, visit all the unvisited

neighbors of z. The newly visited nodes from this level

form a new level that becomes the next current level.

3. Repeat step 2 until no more nodes can be visited.

4. If there are still unvisited nodes, repeat from Step 1.


Illustration of BFS

0 1
0
2 4 2
1
9 4
5 9 10
10 5 7

11 8
6 7 8 11
6
BFS Tree Graph G
Implementation of DFS

Observations:

– the first node visited in each level is the first node

from which to proceed to visit new nodes.

– This suggests that a queue is the proper data structure

to remember the order of the steps.


Illustrate BFS with a Queue

• We will redo the BFS on the previous graph, but this time with

queues

• In Class
BFS (Pseudo Code)

BFS(input: graph G) {
Queue Q; Integer x, z, y;
while (G has an unvisited node x) {
visit(x); Enqueue(x,Q);
while (Q is not empty){
z := Dequeue(Q);
for all (unvisited neighbor y of z){
visit(y); Enqueue(y,Q);
}
}
}
}

You might also like