SlideShare a Scribd company logo
1 of 41
Download to read offline
HARAMAYA UNIVERSITY
SCHOOL OF GRADUATE STUDIES
DEPARTMENT OF COMPUTER SCIENCE
GRAPH DATA STRUCTURE
By: Keno Benti
ID: Sgs/0645/11
JAN 10,2019
Overview
• A Graph is a non-linear data structure, which consists of vertices(or
nodes) connected by edges(or arcs) where edges may be directed
or undirected.
• Graphs are a powerful and versatile data structure that easily allow
you to represent real life relationships between different types of
data (nodes). There are two main parts of a graph:
 The vertices (nodes) where the data is stored
The edges (connections) which connect the nodes
• Vertices i and j are adjacent vertices iff (i, j) is an edge in the
graph
Graph and Its Representations
• The choice of graph representation is said to be situation
specific. It totally depends on the type of operations to be
performed and ease of use.
• Following the most commonly used representations of a graph.
1. Adjacency Matrix
2. Adjacency List
Adjacency Matrix
 is a 2D array of size V x V where V is the number of vertices in a graph. Let the
2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from
vertex i to vertex j.
 Between each pair of vertices, cost of one edge is to be stored. This
shows which vertices are adjacent to one another.
For undirected graphs half of the graph is repeated information. Hence these
matrices are said to be space inefficient.
The memory use of an adjacency matrix is O(n^2) where n = number of
vertices.
Advantages of using adjacency matrix are as follows:
 Easy to understand, implement and convenient to work with.
 Removing an edge involves time complexity of O(1).
 Queries like whether there is an edge from vertex „u‟ to
vertex „v‟ are efficient and require time complexity, O(1).
Disadvantages of using adjacency matrix are as follows:
 Consumes more space O(V^2). Even if the graph is sparse(contains
less number of edges), it consumes the same space. Adding a
vertex is O(V^2) time.
 If the number of nodes in the graph may change, matrix
representation is too inflexible (especially if we don‟t know the
maximal size of the graph).
Adjacency List
• In this representation, every vertex of graph contains list of its adjacent
vertices.
Advantages of using adjacency list are as follows:
• Addition of a vertex and connecting new vertices with the existing ones
is easier.
• Has a space complexity of O(|V|+|E|).
• It allows us to store graph in more compact form and to get the list of
adjacent vertices in O(1) time which is a big benefit for some algorithms.
Cont’d…
Disadvantages of using adjacency list are as follows:
• Queries like whether there is an edge from vertex u to vertex v are not
efficient and require time complexity, O(V).
• It does not allow us to make an efficient implementation, if dynamic
change of vertices number is required.
Types Of Graphs
1. Undirected Graph all edges are undirected or If the connection is
symmetric (in other words A is connected to B ↔ B is connected to
A), then we say the graph is undirected.
2. Directed Graph all edges are directed or If an edge only implies
one direction of connection, we say the graph is directed.
3. Weighted Graph: A weighted graph is a graph where each edge
has an associated numerical value, called weight.
Undirected Graphs
 The pair of vertices representing any edge is unordered. Thus, the
pairs (u,v) and (v,u) represent the same edge.
Example: a graph G2
• V(G2)={0,1,2,3,4,5,6}
• E( G2)={(0,1),(0,2), (1,3),(1,4),(2,5),(2,6)}
• G2 is also a tree that is a special case of graph
• An undirected graph is said to be connected if there is a path
between every pair of vertices in the graph.
Directed Graphs (Digraph)
 each edge is represented by a ordered pairs <u,v>
Example: a graph G3
• V(G3)={0,1,2}
• E(G3)={<0,1>,<1,0>,<1,2>}
• A directed path in a directed graph G is a sequence of distinct
vertices, such that there is an edge from each vertex in the
sequence to the next.
Weighted Graph
• A weighted graph is a graph where each edge has an
associated numerical value, called weight. Weighted graphs
may be either directed or undirected. The weight of the edge
is often referred to as the “cost” of the edge. Example of
weighted graph is:
Graph Traversal Algorithms
Graph traversal means visiting all the nodes of the
graph.
We want to visit every vertex and every edge exactly
once in some well-defined order.
There are two primary traversal algorithms:
• Breadth-First Search (BFS) and
• Depth-First Search (DFS).
DFS/BFS Search Algorithm
SEARCH(Node n):
1. Visit n.
2. Put n's children on a list (Stack or Queue).
3. For each child c in list:
SEARCH(c)
• If we use a Stack and recursive, we get DFS
• If we use a Queue and iterative, we get BFS
BFS-Breadth First Search
 Idea: Visit all children before first grandchild.
• Visiting order: Visit a vertex, then visit all of its neighbors,
then visit all of the neighbors of its neighbors, . . .
• BFS is that a BFS is best used at finding the shortest paths in a given
Graph
• Needs flags or someway to preventing infinite loops:
Weakness
BFS Algorithm
create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbours of u
Example : BFS
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
DFS-Depth First Search
• Idea: Follow a single path to its end, then backtrack
• Is an algorithm for traversing or searching a tree, tree
structure or graph.
• One starts at the root (selecting some node as the root in the
graph case) and explores as far as possible along each branch
before backtracking.
DFS ALGORITHM USING STACK
Example:DFS
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Cont’d…
Graph Traversal Algorithm Complexity
Time Complexity
• BFS Vs DFS Time complexity : O(V+E), when implemented
using the adjacency list. Where V is number of vertices in the
graph and E is number of edges in the graph.
• Space complexity (memory)
BFS :Space complexity is O(|V|) as well - since at worst case
you need to hold all vertices in the queue.
Cont’d…
• DFS: Space Complexity depends on the implementation, a
recursive implementation can have a O(h) space complexity
[worst case], where h is the maximal depth of your tree. But
Depth-first can waste time going down a “rabbit hole”, when
solution is high in tree.
• Worst Case for DFS will be the best case for BFS, and the Best
Case for DFS will be the worst case for BFS.
Conclusion
• A Graph is a non-linear data structure, which consists of vertices(or
nodes) connected by edges(or arcs) where edges may be directed or
undirected.
• Graph is represented by two important ways: Adjacency List and
Adjacency Matrix.
• Graph traversal is a process of checking or updating each vertex in a
graph.
• Graph traversal means visiting each and exactly one node.
• There are two graph traversals: Breadth first Search: Visits the neighbor
vertices before visiting the child vertices and Depth First Search:is used
for traversing a finite graph.
Recommendation
• I recommend for peoples to use hybrid (both BFS and DFS) approach. Because
Worst Case for DFS will be the best case for BFS, and the Best Case for DFS will
be the worst case for BFS in terms of space complexity.
• Building a good general-purpose graph type is surprisingly tricky and difficult.
For this reason, I suggest that you check out existing implementations
(particularly LEDA) before hacking up your own. Note that it costs only time
linear in the size of the larger data structure to convert between adjacency
matrices and adjacency lists. This conversion is unlikely to be the bottleneck in
any application, if you decide you want to use both data structures and have
the space to store them. This usually isn't necessary but might prove simplest if
you are confused about the alternatives.
References
1. Thomas H. Cormen, Charles E. Leirserson, Ronald L. Rivest, Introduction
to algorithms, Cambridge, Massachusetts London, England 2000
2. Manber, U. (1989), Introduction to Algorithms|Creative
Approach, Addison-Wesley, Reading, Massachusetts
3. Danny Sleator, “Parallel and Sequential Data Structures and
Algorithms,15-210 (fall 2013) ”, Sept. 24 , 2013
4. https://www.tutorialspoint.com/data_structures_algorithms/graph_data
_structure.htm
5. https://www.geeksforgeeks.org/graph-and-its-representations/
6. https://hackernoon.com/graphs-in-cs-and-its-traversal-algorithms-
cfee5533f74e
7. https://www.hackerearth.com/practice/algorithms/graphs/depth-first-
search/tutorial/

More Related Content

What's hot (20)

Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Depth first search and breadth first searching
Depth first search and breadth first searchingDepth first search and breadth first searching
Depth first search and breadth first searching
 
Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
B tree
B treeB tree
B tree
 
Graphs In Data Structure
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
 
DFS & BFS Graph
DFS & BFS GraphDFS & BFS Graph
DFS & BFS Graph
 
Binary tree
Binary treeBinary tree
Binary tree
 
Threaded Binary Tree.pptx
Threaded Binary Tree.pptxThreaded Binary Tree.pptx
Threaded Binary Tree.pptx
 
Graph algorithms
Graph algorithmsGraph algorithms
Graph algorithms
 
linked list
linked list linked list
linked list
 
Depth First Search ( DFS )
Depth First Search ( DFS )Depth First Search ( DFS )
Depth First Search ( DFS )
 
Graph theory
Graph theory Graph theory
Graph theory
 
Graphs
GraphsGraphs
Graphs
 
Tree and graph
Tree and graphTree and graph
Tree and graph
 
Graphs data structures
Graphs data structuresGraphs data structures
Graphs data structures
 
Trees
TreesTrees
Trees
 
Dfs
DfsDfs
Dfs
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 

Similar to Graph Data Structure: BFS, DFS Algorithms

Similar to Graph Data Structure: BFS, DFS Algorithms (20)

Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptx
 
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjteUnit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
 
Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashing
 
Graphs
GraphsGraphs
Graphs
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Vanmathy no sql
Vanmathy no sql Vanmathy no sql
Vanmathy no sql
 
VANU no sql ppt.pptx
VANU no sql ppt.pptxVANU no sql ppt.pptx
VANU no sql ppt.pptx
 
graph representation.pdf
graph representation.pdfgraph representation.pdf
graph representation.pdf
 
LEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdf
 
Unit-6 Graph.ppsx ppt
Unit-6 Graph.ppsx                                       pptUnit-6 Graph.ppsx                                       ppt
Unit-6 Graph.ppsx ppt
 
Spanningtreesppt
SpanningtreespptSpanningtreesppt
Spanningtreesppt
 
U1 L5 DAA.pdf
U1 L5 DAA.pdfU1 L5 DAA.pdf
U1 L5 DAA.pdf
 
Graceful labelings
Graceful labelingsGraceful labelings
Graceful labelings
 
ppt 1.pptx
ppt 1.pptxppt 1.pptx
ppt 1.pptx
 
Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
UNIT III.pptx
UNIT III.pptxUNIT III.pptx
UNIT III.pptx
 
Unit ix graph
Unit   ix    graph Unit   ix    graph
Unit ix graph
 
data structures and algorithms Unit 2
data structures and algorithms Unit 2data structures and algorithms Unit 2
data structures and algorithms Unit 2
 
Skiena algorithm 2007 lecture10 graph data strctures
Skiena algorithm 2007 lecture10 graph data strcturesSkiena algorithm 2007 lecture10 graph data strctures
Skiena algorithm 2007 lecture10 graph data strctures
 
Unit 9 graph
Unit   9 graphUnit   9 graph
Unit 9 graph
 

Recently uploaded

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Graph Data Structure: BFS, DFS Algorithms

  • 1. HARAMAYA UNIVERSITY SCHOOL OF GRADUATE STUDIES DEPARTMENT OF COMPUTER SCIENCE GRAPH DATA STRUCTURE By: Keno Benti ID: Sgs/0645/11 JAN 10,2019
  • 2. Overview • A Graph is a non-linear data structure, which consists of vertices(or nodes) connected by edges(or arcs) where edges may be directed or undirected. • Graphs are a powerful and versatile data structure that easily allow you to represent real life relationships between different types of data (nodes). There are two main parts of a graph:  The vertices (nodes) where the data is stored The edges (connections) which connect the nodes • Vertices i and j are adjacent vertices iff (i, j) is an edge in the graph
  • 3. Graph and Its Representations • The choice of graph representation is said to be situation specific. It totally depends on the type of operations to be performed and ease of use. • Following the most commonly used representations of a graph. 1. Adjacency Matrix 2. Adjacency List
  • 4. Adjacency Matrix  is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j.  Between each pair of vertices, cost of one edge is to be stored. This shows which vertices are adjacent to one another. For undirected graphs half of the graph is repeated information. Hence these matrices are said to be space inefficient. The memory use of an adjacency matrix is O(n^2) where n = number of vertices.
  • 5. Advantages of using adjacency matrix are as follows:  Easy to understand, implement and convenient to work with.  Removing an edge involves time complexity of O(1).  Queries like whether there is an edge from vertex „u‟ to vertex „v‟ are efficient and require time complexity, O(1).
  • 6. Disadvantages of using adjacency matrix are as follows:  Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it consumes the same space. Adding a vertex is O(V^2) time.  If the number of nodes in the graph may change, matrix representation is too inflexible (especially if we don‟t know the maximal size of the graph).
  • 7. Adjacency List • In this representation, every vertex of graph contains list of its adjacent vertices. Advantages of using adjacency list are as follows: • Addition of a vertex and connecting new vertices with the existing ones is easier. • Has a space complexity of O(|V|+|E|). • It allows us to store graph in more compact form and to get the list of adjacent vertices in O(1) time which is a big benefit for some algorithms.
  • 8. Cont’d… Disadvantages of using adjacency list are as follows: • Queries like whether there is an edge from vertex u to vertex v are not efficient and require time complexity, O(V). • It does not allow us to make an efficient implementation, if dynamic change of vertices number is required.
  • 9. Types Of Graphs 1. Undirected Graph all edges are undirected or If the connection is symmetric (in other words A is connected to B ↔ B is connected to A), then we say the graph is undirected. 2. Directed Graph all edges are directed or If an edge only implies one direction of connection, we say the graph is directed. 3. Weighted Graph: A weighted graph is a graph where each edge has an associated numerical value, called weight.
  • 10. Undirected Graphs  The pair of vertices representing any edge is unordered. Thus, the pairs (u,v) and (v,u) represent the same edge. Example: a graph G2 • V(G2)={0,1,2,3,4,5,6} • E( G2)={(0,1),(0,2), (1,3),(1,4),(2,5),(2,6)} • G2 is also a tree that is a special case of graph • An undirected graph is said to be connected if there is a path between every pair of vertices in the graph.
  • 11. Directed Graphs (Digraph)  each edge is represented by a ordered pairs <u,v> Example: a graph G3 • V(G3)={0,1,2} • E(G3)={<0,1>,<1,0>,<1,2>} • A directed path in a directed graph G is a sequence of distinct vertices, such that there is an edge from each vertex in the sequence to the next.
  • 12. Weighted Graph • A weighted graph is a graph where each edge has an associated numerical value, called weight. Weighted graphs may be either directed or undirected. The weight of the edge is often referred to as the “cost” of the edge. Example of weighted graph is:
  • 13. Graph Traversal Algorithms Graph traversal means visiting all the nodes of the graph. We want to visit every vertex and every edge exactly once in some well-defined order. There are two primary traversal algorithms: • Breadth-First Search (BFS) and • Depth-First Search (DFS).
  • 14. DFS/BFS Search Algorithm SEARCH(Node n): 1. Visit n. 2. Put n's children on a list (Stack or Queue). 3. For each child c in list: SEARCH(c) • If we use a Stack and recursive, we get DFS • If we use a Queue and iterative, we get BFS
  • 15. BFS-Breadth First Search  Idea: Visit all children before first grandchild. • Visiting order: Visit a vertex, then visit all of its neighbors, then visit all of the neighbors of its neighbors, . . . • BFS is that a BFS is best used at finding the shortest paths in a given Graph • Needs flags or someway to preventing infinite loops: Weakness
  • 16. BFS Algorithm create a queue Q mark v as visited and put v into Q while Q is non-empty remove the head u of Q mark and enqueue all (unvisited) neighbours of u
  • 26. DFS-Depth First Search • Idea: Follow a single path to its end, then backtrack • Is an algorithm for traversing or searching a tree, tree structure or graph. • One starts at the root (selecting some node as the root in the graph case) and explores as far as possible along each branch before backtracking.
  • 37. Graph Traversal Algorithm Complexity Time Complexity • BFS Vs DFS Time complexity : O(V+E), when implemented using the adjacency list. Where V is number of vertices in the graph and E is number of edges in the graph. • Space complexity (memory) BFS :Space complexity is O(|V|) as well - since at worst case you need to hold all vertices in the queue.
  • 38. Cont’d… • DFS: Space Complexity depends on the implementation, a recursive implementation can have a O(h) space complexity [worst case], where h is the maximal depth of your tree. But Depth-first can waste time going down a “rabbit hole”, when solution is high in tree. • Worst Case for DFS will be the best case for BFS, and the Best Case for DFS will be the worst case for BFS.
  • 39. Conclusion • A Graph is a non-linear data structure, which consists of vertices(or nodes) connected by edges(or arcs) where edges may be directed or undirected. • Graph is represented by two important ways: Adjacency List and Adjacency Matrix. • Graph traversal is a process of checking or updating each vertex in a graph. • Graph traversal means visiting each and exactly one node. • There are two graph traversals: Breadth first Search: Visits the neighbor vertices before visiting the child vertices and Depth First Search:is used for traversing a finite graph.
  • 40. Recommendation • I recommend for peoples to use hybrid (both BFS and DFS) approach. Because Worst Case for DFS will be the best case for BFS, and the Best Case for DFS will be the worst case for BFS in terms of space complexity. • Building a good general-purpose graph type is surprisingly tricky and difficult. For this reason, I suggest that you check out existing implementations (particularly LEDA) before hacking up your own. Note that it costs only time linear in the size of the larger data structure to convert between adjacency matrices and adjacency lists. This conversion is unlikely to be the bottleneck in any application, if you decide you want to use both data structures and have the space to store them. This usually isn't necessary but might prove simplest if you are confused about the alternatives.
  • 41. References 1. Thomas H. Cormen, Charles E. Leirserson, Ronald L. Rivest, Introduction to algorithms, Cambridge, Massachusetts London, England 2000 2. Manber, U. (1989), Introduction to Algorithms|Creative Approach, Addison-Wesley, Reading, Massachusetts 3. Danny Sleator, “Parallel and Sequential Data Structures and Algorithms,15-210 (fall 2013) ”, Sept. 24 , 2013 4. https://www.tutorialspoint.com/data_structures_algorithms/graph_data _structure.htm 5. https://www.geeksforgeeks.org/graph-and-its-representations/ 6. https://hackernoon.com/graphs-in-cs-and-its-traversal-algorithms- cfee5533f74e 7. https://www.hackerearth.com/practice/algorithms/graphs/depth-first- search/tutorial/