graph algorithm - skku
TRANSCRIPT
Introduction
2
Graph: Represents pair-wise relationship between a set of objects
1. Vertex (nodes)
2. Edges (arc)
Edge
Vertex
Introduction
3
Directed Graph (di-graph): have pair of ordered vertices (u,v)
Un-Directed Graph: have pair of unordered vertices, (u,v) and (v,u) are same
Graph Applications
4
1. Social Networks – Facebook, LinkedIn, etc
2. City-Road Network
City
B
City
C
City
A
3. Precedence Constraints
Task
B
Task
C
Task
ASuccess Failure
Graph Representation
5
There are generally two ways to represent a graph data structure
• Adjacency Matrix
• Adjacency List
Graph Representation
6
Adjacency Matrix: Represents graph with ‘V’ nodes into an VxV 0-1 matrix where Aij=1 means that vertex ‘i’ and ‘j’ are connected.
Example
Graph Adjacency Matrix
Graph Representation
7
Adjacency Matrix
Pros:
• Easy to implement.
• Removing an edge takes O(1) time.
• Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1) Search
Graph Representation
8
Adjacency Matrix
Cons:
• Consumes more spaces O(V2).
• Adding a vertex is O(V2) if there is to add a new vertex, one has to increase the storage for a |V|² matrix to (|V|+1)²
Graph Representation
9
Adjacency List: An array of linked lists is used. Size of the array is equal to number of vertices and each entry of array corresponds to a linked list of vertices adjacent to the index
Example
Adjacency ListGraph
Graph Representation
10
Adjacency List
Pros:
• Saves space O(|V|+|E|), worst case O(V2).
• Adding a vertex is easier.
Graph Representation
11
Adjacency List
Cons:
• Queries like whether there is an edge from vertex u to vertex v are not efficient and can be done O(V) Search
Breadth First Search
15
Idea: Traverse nodes in layersL1
L2
L3
L4
Problem: Since we have cycles, each node will be visited infinite times.
Solution: Use a Boolean visited array.
Depth First Search
30
Idea: To go forward (in depth) while there is any such possibility, if not then, backtrack
Problem: Since we have cycles, each node may be visited infinite times.
Solution: Use a Boolean visited array.
Reference
• Charles Leiserson and Piotr Indyk, “Introduction to Algorithms”, September 29, 2004
• https://www.geeksforgeeks.org