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

Data Structures & Algorithms ppt 4

The document provides an overview of graphs as a non-linear data structure consisting of vertices and edges, detailing their properties, terminology, representations, and traversal methods like Depth First Search (DFS) and Breadth First Search (BFS). It also covers Dijkstra's algorithm for finding the shortest paths in graphs, along with its applications and limitations. The content is aimed at understanding graph theory and its practical uses in various fields such as navigation and network routing.

Uploaded by

yaapono61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Data Structures & Algorithms ppt 4

The document provides an overview of graphs as a non-linear data structure consisting of vertices and edges, detailing their properties, terminology, representations, and traversal methods like Depth First Search (DFS) and Breadth First Search (BFS). It also covers Dijkstra's algorithm for finding the shortest paths in graphs, along with its applications and limitations. The content is aimed at understanding graph theory and its practical uses in various fields such as navigation and network routing.

Uploaded by

yaapono61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

GRAPHS

ALEX OFORI KARIKARI


WHAT IS A GRAPH?
• A graph is a non-linear data structure that comprises a collection of vertices
(nodes) and edges (connections) between them.
• A vertex, also called a node, is a point or an object in the
Graph, and an edge is used to connect two vertices with each
other
• Graphs are non-linear because the data structure allows us to
have different paths to get from one vertex to another, unlike
with linear data structures like Arrays or Linked Lists.
Graphs are used to represent and solve problems where the data consists of
objects and relationships between them, such as:
• Social Networks: Each person is a vertex, and relationships (like friendships) are
the edges. Algorithms can suggest potential friends.
• Maps and Navigation: Locations, like a town or bus stops, are stored as vertices,
and roads are stored as edges. Algorithms can find the shortest route between
two locations when stored as a Graph.
• Internet: Can be represented as a Graph, with web pages as vertices and
hyperlinks as edges.
• Biology: Graphs can model systems like neural networks or the spread of
diseases
GRAPH PROPERTIES

A weighted Graph is a Graph where the edges have values. The weight
value of an edge can represent things like distance, capacity, time, or
probability.
A connected Graph is when all the vertices are connected through edges
somehow. A Graph that is not connected, is a Graph with isolated (disjoint)
subgraphs, or single isolated vertices.
• A directed Graph, also known as a digraph, is when the edges between
the vertex pairs have a direction. The direction of an edge can represent
things like hierarchy or flow.
GRAPH TERMINOLOGY

Directed Graph (Digraph): A graph in which the edges have a direction,


indicating a one-way relationship between vertices.

Undirected Graph: A graph in which the edges do not have a direction,


indicating a two-way relationship.

Weighted Graph: A graph in which edges have weights assigned to them,


typically representing costs, lengths, or capacities.

Unweighted Graph: A graph in which edges do not have weights.

Adjacent (Neighbors): Two vertices are adjacent if there is an edge


connecting them.
GRAPH TERMINOLOGY Cont.

Cycle: A path that starts and ends at the same vertex without traversing any edge more than once.

Loop: An edge that connects a vertex to itself.

Subgraph: A graph formed from a subset of the vertices and edges of another graph.

Connected Graph: An undirected graph is connected if there is a path between every pair of
vertices.

Disconnected Graph: A graph is disconnected if it is not connected, i.e., if there are at least two
vertices with no path between them.

Complete Graph: A graph in which there is an edge between every pair of vertices.
GRAPH TERMINOLOGY cont.
Path: A sequence of edges that allows you to go from one
vertex to another.

Degree: The degree of a vertex is the number of edges


connected to it. For directed graphs, there are in-
degree (edges coming into the vertex) and out-
degree (edges going out from the vertex).

Tree: A connected, undirected graph with no cycles.

Acyclic Graph: A graph with no cycles. In the context of


directed graphs, it is often called a Directed Acyclic Graph
(DAG).

Bipartite Graph: A graph whose vertices can be divided


into two disjoint sets such that every edge connects a
vertex in one set to a vertex in the other set.
GRAPH
REPRESENTATIONS
A Graph representation tells us how a Graph is stored in
memory.
Different Graph representations can:

• take up more or less space.


• be faster or slower to search or manipulate.
• be better suited depending on what type of Graph we have
(weighted, directed, etc.), and what we want to do with the
Graph.

• be easier to understand and implement than others


GRAPH TRAVERSALS

• To traverse a Graph means to start in one vertex and go


along the edges to visit other vertices until all vertices, or as
many as possible, have been visited.
F
A C

B
D E

G
Understanding how a Graph can be traversed is important for
understanding how algorithms that run on Graphs work.
The two most common ways a Graph can be traversed are:
• Depth First Search (DFS)
• Breadth First Search (BFS)
• DFS is usually implemented using a Stack or recursion (which utilizes
the call stack), while BFS is usually implemented using a Queue.

The Call Stack keeps functions running in the correct order.


• If for example, FunctionA calls FunctionB, FunctionB is placed on top of
the call stack and starts running. Once FunctionB is finished, it is
removed from the stack, and then FunctionA resumes its work.
DEPTH -FIRST SEARCH TRAVERSAL

Depth First Search is said to go "deep" because it visits a vertex,


then an adjacent vertex, and then that vertex' adjacent vertex, and
so on, and in this way the distance from the starting vertex
increases for each recursive iteration

How it works:

Start DFS traversal on a vertex.

Do a recursive DFS traversal on each of the adjacent vertices as


long as they are not already visited
F
A C

B
D E

Result: D, A, C, B, F, E, G
The DFS traversal starts in vertex D and marks it as visited. Then, for every
new vertex visited, the traversal method is called recursively on all adjacent
vertices that have not been visited yet. So when vertex A is visited in the
diagram above, vertex C or vertex E (depending on the implementation) is the
next vertex where the traversal continues.
IMPLEMENTATION
# Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7’],
'3' : ['2', '4’],
'7' : ['8’],
'2' : [],
'4' : ['8’],
'8' : []
}
PYTHON visited = set() # Set to keep track of visited nodes of graph.
IMPLEMENTATION
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node) visited.add(node)
for neighbour in graph[node]: dfs(visited, graph,
neighbour)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
APPLICATIONS OF DEPTH-FIRST SEARCH

Pathfinding Topological Cycle Puzzle solving


a. Finding paths in sorting
a. Ordering tasks detection
a. Identifying cycles a. Solving puzzles
mazes or grids based on in graphs with a single solution
b. Determining dependencies b. Dependency b. Backtracking
connectivity in b. Scheduling and resolution
networks dependency
management
APPLICATIONS OF DFS CONT.

• Web crawlers
• Model checking
• Testing if graph is bipartite
• Finding strongly connected components
BREATH-FIRST SEARCH (BFS)

Breadth First Search visits all adjacent vertices of a vertex before visiting neighboring
vertices to the adjacent vertices. This means that vertices with the same distance from the
starting vertex are visited before vertices further away from the starting vertex are visited.

How it works:

1. Put the starting vertex into the queue.

2. For each vertex taken from the queue, visit the vertex, then put all unvisited adjacent
vertices into the queue.

3. Continue as long as there are vertices in the queue.


F
A C

D E

Result: D, A, C, E, B, F, G
BFS traversal visits vertices the same distance from the starting
vertex, before visiting vertices further away. So for example,
after visiting vertex A, vertex E and C are visited before visiting
B, F and G because those vertices are further away.
• Breadth First Search traversal works this way by putting all
adjacent vertices in a queue (if they are not already visited),
and then using the queue to visit the next vertex.
IMPLEMENTATION
graph = {
'5' : ['3’, '7’],
'3' : ['2', '4’],
'7' : ['8’],
'2' : [],
'4' : ['8’],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
PYTHON
IMPLEMENTATION def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node m =
queue.pop(0) print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour) queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search") bfs(visited,
graph, '5') # function calling
APPLICATIONS FOR BFS

1. In GPS navigation, it helps in finding the shortest path available


from one point to another.
2. In pathfinding algorithms
3. Cycle detection in an undirected graph
4. In minimum spanning tree
5. To build index by search index
6. In Ford-Fulkerson algorithm to find maximum flow in a network
• Differences
between DFS and
BFS
• Differences
between DFS and
BFS
SIMILARITIES:

1 2 3 4 5

Graph Finds all reachable Work on both Can be used for Time
Traversal: Both BFS vertices: Both directed and searching: Both Complexity: In the
and DFS are used to algorithms can find undirected algorithms can be worst-case scenario,
traverse or explore all the vertices graphs: Both used to find a both algorithms have
all nodes in a graph. reachable from a algorithms can be specific node or a time complexity of
starting vertex. used on both element within a O(V + E), where V is
directed and graph. the number of
undirected graphs. vertices (nodes) and
E is the number of
edges in the graph.
… Is a well-known algorithm in computer
science used to find the shortest paths
from a starting node to all other nodes in
a graph, especially when the graph has a
non-negative edge weights.

DIJKSTRA'S
ALGORITH Purpose:

M
The primary function of Dijkstra's
algorithm is to determine the shortest
paths (or distances) from a designated
source node to every other node within a
graph.
Dijkstra's algorithm finds the shortest paths
from a starting node (source) to all other
nodes in a graph,

using the formula


DIJKSTRA'S
ALGORITH distance[v] =
M
FORMULA min(distance[v], distance[u] + weight(u, v))

if distance[u] + weight(u, v) < distance[v].


distance[v] represents the shortest known distance from the
source node to node v.

distance[u] represents the shortest known distance from the


Formula source node to node u.

Explanatio weight(u, v) represents the weight (or cost) of the edge

n: connecting nodes u and v.

The formula distance[v] = min(distance[v], distance[u] +


weight(u, v)) checks if the path from the source
to v through u is shorter than the currently known shortest path
to v.

If it is, the distance to v is update


• How to find Shortest
Paths from Source to all
Vertices using
Dijkstra’s Algorithm
Output: 0 4 12 19 21 11 9 8 14
Explanation: Shortest Paths:
0 to 1 = 4.
0 to 2 = 12. 0->1->2

EXAMPLE: 0 to 3 = 19. 0->1->2->3


0 to 4 = 21. 0->7->6->5->4
0 to 5 = 11. 0->7->6->5
0 to 6 = 9. 0->7->6
0 to 7 = 8. 0->7
0 to 8 = 14. 0->1->2->8
Dijkstra's algorithm is used in various
applications,

including:

APPLICATIO Navigation: Finding the shortest routes in


NS road networks.
Network Routing: Determining the shortest
paths for data packets in computer
networks.
Resource Allocation: Optimizing resource
allocation in various systems.
LIMITATIONS:

• Dijkstra's algorithm is not suitable


for graphs with negative edge
weights, as it can lead to incorrect
results.
END OF SESSION

You might also like