Graph
Graph
✔ Adjacency List
Adjacency matrix
✔ A way of representing a graph as a matrix of
booleans (0's and 1's).
✔ represented in the form of a square matrix on
a computer
✔ boolean value of the matrix indicates if there
is a direct path between two vertices.
Adjacency matrix
Adjacency List
RT={(d,b)}
Transitive closure
R={(a,b),(d,b),(b,d)}
RT={(a,d),(d,d),((b,b)}
Transitive closure
R={(a,d),(b,d),(d,d),(d,a),(d,b),(d,c)}
RT={(a,a),(a,b),(a,c),(b,a),(b,d),(b,c),(d,b),(d,c),
(d,d)}
DEPTH FIRST SEARCH(DFS)
• Take the top item of the stack and add it to the visited list.
• Create a list of that vertex's adjacent nodes. Add the ones which
aren't in the visited list to the top of the stack.
Visited 0 1 2 4 3
DEPTH FIRST SEARCH(DFS)
Adjacency Matrix
A B C D E F
A 0 1 1 1 0 0
B 1 0 0 0 1 1
C 1 0 0 0 0 1 visited A B E F C D
D 1 0 0 0 0 0
E 0 1 0 0 0 0
F 0 1 1 0 0 0
Breadth first search(BFS)
.
SPANNING TREE
Minimum Spanning Tree
Prims Algorithm
Kruskal Algorithm
PRIMS ALGORITHM
Prim’s Algorithm is a famous greedy
algorithm.
It is used for finding the Minimum Spanning
Tree (MST) of a given graph.
To apply Prim’s algorithm, the given graph
must be weighted, connected and undirected.
PRIMS ALGORITHM
• Step-01:
•
• Randomly choose any vertex.
• The vertex connecting to the edge having least weight is usually
selected.
•
• Step-02:
•
• Find all the edges that connect the tree to new vertices.
• Find the least weight edge among those edges and include it in
the existing tree.
• If including that edge creates a cycle, then reject that edge and
look for the next least weight edge
PRIMS ALGORITHM
• Step-03:
•
• Keep repeating step-02 until all the vertices are
included and Minimum Spanning Tree (MST) is
obtained.
•
• Prim’s Algorithm Time Complexity-
•
• Worst case time complexity of Prim’s Algorithm is-
• O(ElogV) using binary heap
• O(E + VlogV) using Fibonacci heap
PRIMS ALGORITHM
1 2 28
✔ 1 6 10
PRIMS ALGORITHM
1 2 28
✔ 1 6 25
✔ 6 5 25
PRIMS ALGORITHM
1 2 28
✔ 1 6 25
✔ 6 5 25
✔ 54 22
57 24
PRIMS ALGORITHM
1 2 28
✔ 1 6 25
✔ 6 5 25
✔ 54 22
57 24
4 7 18
✔ 4 3 12
PRIMS ALGORITHM
12 28
✔ 16 25
✔ 65 25
✔ 54 22
57 24
47 18
✔ 43 12
✔ 32 16
PRIMS ALGORITHM
12 28
✔ 16 25
✔ 65 25
✔ 54 22
57 24
47 18
✔ 43 12
✔ 32 16 Since all the vertices have been included in the
MST, so we stop.
✔ 27 14
Now, Cost of Minimum Spanning Tree
= Sum of all edge weights
= 10 + 25 + 22 + 12 + 16 + 14
= 99 units
PRIMS ALGORITHM
PRIMS ALGORITHM