Professional Documents
Culture Documents
Graphs
Everytime I do it makes me Laugh
WMSU
• Complete graph: a
graph in which every
vertex is directly
connected to every
other vertex
Directed Graph Big O
• What is the number of edges
in a complete directed graph
with N vertices?
Vertices = N
Edges = N * (N-1)
=N*N–N*1
= N2 – N * 1
= O(N2)
Undirected Graph Big O
• What is the number of edges in a complete
undirected graph with N vertices?
Vertices = N
Edges = N * (N-1)
2
= (N * N – N * 1) / 2
= (N2 – N * 1) / 2
= O(N2)
Python Implementation of Graphs
• Array-based implementation
– A 1D array is used to represent
the vertices
– A 2D array (adjacency matrix)
is used to represent the edges
Python Implementation of Graphs
• Vertices and Indices can both be represented by 2D
Arrays, called an Adjacency Matrix
Python Implementation of Graphs
• Alternatively, Graphs in Python can be represented as a
dict of sets
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
Python Implementation of Graphs
• Creating a Graph Object in Python:
Python Implementation of Graphs
• Adding Vertices to Graphs
Python Implementation of Graphs
• Adding Edges between 2 Vertices (Undirected)
Python Implementation of Graphs
• Printing Edges between Vertices
Breadth First Search
Breadth First Search
•• Steps
Step
Step 6:7:5:
Step1:
Step2: Remove
Remove
3:
4: Remove
Initially
Push node
node
node34node
queue from
from0 intothe
the
and1
2 front
0front
fromofofqueue
queue queue
the
visited and and
and
front
arrays
markvisit
visit
ofarethe
the
queueunvisited
it unvisited
and visit
visited.
empty.
neighbours and push them into queue.
theweunvisited
As can see thatneighbours
every neighbours and push
of node 4 isthem
3 are into
visited,
visited, queue.
sosomove
move totothe
thenext
next
node that is
areininthe
thefront
frontofofthe
thequeue.
queue.
Breadth First Search
Depth First Search
Depth First Search
• Step
Step
Step1:2:
Step4:
3:
5: Visit
6:Now,
Now,Node
Initially 0Node
and 1
stack
2put
43 its
atand
atthe adjacent
thevisited
top thenodes
topofofthe stack,
arrays which
so
areso
stack, visitare
empty.
visit not
node
node 1
243
and pop
popyet
visited
and itit from
from the
into the stack
thestack
stack.andand put
put all
all of
of its
its adjacent
adjacent nodes
nodes
which are
which are not not visited
visited (i.e,
in
in the
the3,stack.
stack.
4) in the stack.
Depth First Search