Graphs
Graphs
Learning Outcome
Successful students should be able to:
Define graph and terminology
Describe graph representation method
Show how to the graph traversal
Describe how to use graph in real world application
Linear data structure
Non Linear Data structure
What are graphs?
■ Set of nodes and connections between them.
Types of graphs
■ Undirected graph: A link is both ways
■ Example : Facebook (friends)
Types of graphs
■ Directed graph (Digraph): Each link is directional and
does not imply the inverse.
■ Eg: Web crawling
■ We say G=(V,E).
■ Think n for node if you find it hard to remember which way around these are.
Visualisation
■ A graph G=(V,E)
■ Where :
– V={1,2,3,4,5}
– E={{1,2},{2,4},{3,4},{3,5},{4,5}}
Implementing Graphs
■ There are two ways of implementing a graph when programming.
■ Adjacency Matrix:
– A two dimensional matrix of boolean values where the value
of a cell i, j is true if vertices i and j are connected.
■ Adjacency List:
– Each vertex contains a list of vertices that it is connected to.
Adjacency Matrix
■ Note reflection around i=j, due to undirectedness.
■ The adjacency list must store the edges as pairs including the connection
and the weight.
Adjacency Matrix (2D dimensional array)
Adjacency List (Array of linked list)
Graph Traversal
■ Storing data in a graph is fairly easy.
■ depthFirstSearch(G,v)
– Not searching for v, even though this is
what it reads like…
Depth-First Search (DFS)
■ Traverses a graph by visiting each vertex in turn.
■ Could have been different, but the edge ordering from each node is arbitrary.
■ https://www.cs.usfca.edu/~galles/visualization/DFS.html
■ https://visualgo.net/en/dfsbfs?slide=1
Breadth-First Search (BFS)
■ Traverses the graph by searching every edge from the current
vertex.
■ Only moves to the next vertex in the graph when all edges have
been explored.
■ https://www.cs.usfca.edu/~galles/visualization/BFS.html
Application of graph in real world application
Analysing related
Map analysis,
Ranking search data, such as
route finding,
results social networks,
path planning
proteins, etc.
Constraint Physics
Compiler
satisfaction simulations
optimisation
(timetabling) (actual physics)
Social
Physics
connections:
simulations
Facebook uses
(games)
graphs for this