SlideShare une entreprise Scribd logo
1  sur  24
CS 6213 –
Advanced
Data
Structures
Lecture 2
GRAPHS AND THEIR
REPRESENTATION
TREES, PATHS, CYCLES
TOPOLOGICAL SORTING
 Instructor
Prof. Amrinder Arora
amrinder@gwu.edu
Please copy TA on emails
Please feel free to call as well
 TA
Iswarya Parupudi
iswarya2291@gwmail.gwu.edu
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 2
LOGISTICS
L4 - BTrees CS 6213 - Advanced Data Structures - Arora 3
CS 6213
Basics
Record /
Struct
Arrays / Linked
Lists / Stacks
/ Queues
Graphs / Trees
/ BSTs
Advanced
Trie, B-Tree
Splay Trees
R-Trees
Heaps and PQs
Union Find
 Graphs – Basics
 Degrees, Number of Edges, Min/Max Degree
 Kinds of Graphs
 How to Represent in Data Structures
 Trees, Paths, Cycles
 Journeys
 Topological Sorting, DAGs
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 4
AGENDA
 A graph G=(V,E) consists of a finite set V, which is the
set of vertices, and set E, which is the set of edges.
Each edge in E connects two vertices v1 and v2,
which are in V.
 Can be directed or undirected
Not to be confused with a bar graph!!!! 
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 5
GRAPH
A core data structure that shows up in many
circumstances:
 Transportation and Logistics (paths, etc.)
 Circuit Design
 Social Networking – Model connections between people
 Sociology – Model influence
 Zoology and Wildlife
 Project Task Management
 Job Scheduling and Resource Assignment (matching)
 Time table scheduling
 Task parallelization (graph coloring)
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 6
GRAPH – APPLICATIONS
 (Undirected) Degree of a node
 (Directed) Indegree / Outdegree
 Min degree in a graph: 
 Max degree in a graph: 
 Basic observations
 (Undirected) Sum of degrees = 2 x number of edges
 (Directed) Sum of indegree = Sum of outdegree = number of
edges
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 7
DEGREE
 If (x,y) is an edge, then x is said to be adjacent to y, and y is adjacent
from x.
 In the case of undirected graphs, if (x,y) is an edge, we just say that x
and y are adjacent (or x is adjacent to y, or y is adjacent to x). Also, we
say that x is the neighbor of y.
 The indegree of a node x is the number of nodes adjacent to x
 The outdegree of a node x is the number of nodes adjacent from x
 The degree of a node x in an undirected graph is the number of
neighbors of x
 A path from a node x to a node y in a graph is a sequence of node x,
x1,x2,...,xn,y, such that x is adjacent to x1, x1 is adjacent to x2, ..., and xn
is adjacent to y.
 The length of a path is the number of its edges.
 A cycle is a path that begins and ends at the same node
 The distance from node x to node y is the length of the shortest path
from x to y.
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 8
GRAPH DEFINITIONS
 Using a matrix A[1..n,1..n] where A[i,j] = 1 if (i,j) is an
edge, and is 0 otherwise. This representation is called
the adjacency matrix representation. If the graph is
undirected, then the adjacency matrix is symmetric about
the main diagonal.
 Using an array Adj[1..n] of pointers, which Adj[i] is a
linked list of nodes which are adjacent to i.
 The matrix representation requires more memory, since it
has a matrix cell for each possible edge, whether that
edge exists or not. In adjacency list representation, the
space used is directly proportional to the number of
edges.
 If the graph is sparse (very few edges), then adjacency
list may be a more efficient choice.
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 9
GRAPH REPRESENTATIONS
 A very practical choice is to use graphing libraries,
such as:
 JGraphT (Java)
 Boost (C++)
 GraphStream (Java)
 JUNG (Java)
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 10
GRAPH REPRESENTATION (CONT.)
 Graphs can be characterized in many ways. Two
important ones being:
 Directed or Undirected
 Weighted or Unweighted
 Both Adjacency Matrix (AM) and Adjacency List (AL)
representations can be used for graphs – weighted
or unweighted, directed or undirected.
 A[i,j] = A[j,i] if graph is undirected. So, we could decide to use
just the upper triangle.
 If graph is weighted, in adjacency list, we can also store the
weight. AL[i] = [(j,w(i,j)), (k,w(i,k)), …]
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 11
GRAPH CHARACTERIZATIONS
 A tree is a connected acyclic graph (i.e., it has no
cycles)
 Rooted tree: A tree in which one node is designated
as a root (the top node)
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 12
TREE
Example:
Node A is root node
F and D are child nodes of A.
P and Q are child nodes of J.
Etc.
 Definitions
 Leaf is a node that has no children
 Ancestors of a node x are all the nodes on the path from x to
the root, including x and the root
 Subtree rooted at x is the tree consisting of x, its children and
their children, and so on and so forth all the way down
 Height of a tree is the maximum distance from the root to any
node
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 13
TREE (CONT.)
Option 1
•Trees are
graphs, so we
can use
standard graph
representation
– Adjacency
Matrix or
Adjacency List
Option 2
•Use parent
node and list
for child nodes
Option 3
•Use parent
node, and two
pointers – one
for first child
and the other
for nextSibling
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 14
REPRESENTING TREES
3 Basic Options
 We can use standard graph representation –
Adjacency Matrix or Adjacency List
 These options are overkill for trees, but in some
instances, the graph is not known to be a tree
beforehand, so this option works.
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 15
TREE REPRESENTATION – OPTION 1
 Rather than using Adjacency Matrix
or Adjacency List representation,
we can use a simpler representation
 Each node has a pointer to parent,
and a linked list of child nodes
 The root node’s parent pointer is null
 This representation works for “rooted” trees. If the
tree is not rooted, we can designate one node as
root.
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 16
TREE REPRESENTATION – OPTION 2
Node {
Node parent,
List<Node> childNodes
}
 Another representation for Trees: Left
Child, Right Sibling representation for a
tree. Each node has 3 pointers:
 Parent – Points to parent (null if this is the root
node)
 Left pointer – Points to first child (null if this is
a leaf node)
 Right pointer – Points to right sibling (null if no
more siblings)
 For example:
 is represented by
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 17
TREE REPRESENTATION – OPTION 3
Node {
Node parent,
Node firstChild,
Node nextSibling
}
 When updating values in a tree, such as the size of the
subtree rooted at a node, the weight of the subtree
rooted at a node, etc, there are two main methods:
 Recompute whenever there is a modify operation (addition of a
node, deletion of a node, changing the weight of a node, etc).
Recomputations usually only need to propagate from the change
node upwards to the root. [Advantage: Values always up to date,
Disadvantages: Lot of time spent in Recompute, Method cannot
be run concurrently.]
 Use a dirty flag and set to true when there is a change. Set dirty
flag to true for all ancestors (navigate to parent, until the root).
Recompute when there is a need, or as per a schedule.
[Advantages: Efficient, Methods (other than the “recomputed”
operation can be run concurrently. Disadvantages: Values are out
of date at times.]
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 18
UPDATING VALUES
 Able to hold the entire graph in memory?
 If your graph is large and changing fast, like the
Facebook interconnection graph, you simply cannot
hold it in memory using traditional methods. You
need to replicate it across multiple servers and use
reliable services to get partial data out from the
graph. Your graph may simply be backed by a
database with which you interact directly (without
ever loading a complete “graph” object.)
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 19
LARGE GRAPHS
 Given each of the graph representations, how do we
find a path?
 Shortest path algorithms
 Dijkstra
 All Pairs Shortest Paths
 [Refer to CS 6212 Notes for details]
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 20
PATHS
 Path, spread over time
 Useful concept if the graph changes over time
 Specifically, consider this scenario:
 Edge e1 existed from x to y at time t1
 Edge e2 existed from y to z at time t2
 t1 < t2
 Then, we say that there exists a journey from x to z
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 21
JOURNEY
 How can we detect cycles in a graph?
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 22
CYCLES
 Assuming a graph is a Directed Acyclic Graph,
topological ordering can be produced in linear time.
O(n + m)
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 23
TOPOLOGICAL SORTING
 Graphs are important data structures with numerous
applications
 Graphs can be of different kinds
 Many convenient ways to model graphs
 Adjacency Matrix
 Adjacency List
 Special structures for trees
 Many commercial and open source libraries exist, such as
JGraphT
CS 6213 – Arora – L2 Advanced Data Structures - Graphs 24
SUMMARY

Contenu connexe

Tendances

Adjacency list
Adjacency listAdjacency list
Adjacency list
Stefi Yu
 

Tendances (20)

17. Trees and Graphs
17. Trees and Graphs17. Trees and Graphs
17. Trees and Graphs
 
Red black trees presentation
Red black trees presentationRed black trees presentation
Red black trees presentation
 
4.4 hashing
4.4 hashing4.4 hashing
4.4 hashing
 
Adjacency list
Adjacency listAdjacency list
Adjacency list
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 
Network layer
Network layerNetwork layer
Network layer
 
Heap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap AlgorithmHeap Sort || Heapify Method || Build Max Heap Algorithm
Heap Sort || Heapify Method || Build Max Heap Algorithm
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
 
The medium access sublayer
 The medium  access sublayer The medium  access sublayer
The medium access sublayer
 
Bridge
BridgeBridge
Bridge
 
Transportlayer tanenbaum
Transportlayer tanenbaumTransportlayer tanenbaum
Transportlayer tanenbaum
 
B tree
B treeB tree
B tree
 
RABIN KARP ALGORITHM STRING MATCHING
RABIN KARP ALGORITHM STRING MATCHINGRABIN KARP ALGORITHM STRING MATCHING
RABIN KARP ALGORITHM STRING MATCHING
 
Transport layer protocols : TCP and UDP
Transport layer protocols  : TCP and UDPTransport layer protocols  : TCP and UDP
Transport layer protocols : TCP and UDP
 
Polynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptxPolynomial reppresentation using Linkedlist-Application of LL.pptx
Polynomial reppresentation using Linkedlist-Application of LL.pptx
 
Graph algorithm
Graph algorithmGraph algorithm
Graph algorithm
 
The Transport Layer
The Transport LayerThe Transport Layer
The Transport Layer
 
Network layer tanenbaum
Network layer tanenbaumNetwork layer tanenbaum
Network layer tanenbaum
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture Notes
 
Breadth first search
Breadth first searchBreadth first search
Breadth first search
 

En vedette

Discrete maths assignment
Discrete maths assignmentDiscrete maths assignment
Discrete maths assignment
Keshav Somani
 
Vertex edge graphs
Vertex edge graphsVertex edge graphs
Vertex edge graphs
emteacher
 
Matrix Representation Of Graph
Matrix Representation Of GraphMatrix Representation Of Graph
Matrix Representation Of Graph
Abhishek Pachisia
 

En vedette (20)

Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
Discrete maths assignment
Discrete maths assignmentDiscrete maths assignment
Discrete maths assignment
 
Talk on Graph Theory - I
Talk on Graph Theory - ITalk on Graph Theory - I
Talk on Graph Theory - I
 
Talk on Standard Template Library
Talk on Standard Template LibraryTalk on Standard Template Library
Talk on Standard Template Library
 
Graph theory1234
Graph theory1234Graph theory1234
Graph theory1234
 
Vertex Edge Graphs
Vertex Edge GraphsVertex Edge Graphs
Vertex Edge Graphs
 
Vertex edge graphs
Vertex edge graphsVertex edge graphs
Vertex edge graphs
 
Cinterviews Binarysearch Tree
Cinterviews Binarysearch TreeCinterviews Binarysearch Tree
Cinterviews Binarysearch Tree
 
Time complexity of union find
Time complexity of union findTime complexity of union find
Time complexity of union find
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
Algorithmic Puzzles
Algorithmic PuzzlesAlgorithmic Puzzles
Algorithmic Puzzles
 
Euclid's Algorithm for Greatest Common Divisor - Time Complexity Analysis
Euclid's Algorithm for Greatest Common Divisor - Time Complexity AnalysisEuclid's Algorithm for Greatest Common Divisor - Time Complexity Analysis
Euclid's Algorithm for Greatest Common Divisor - Time Complexity Analysis
 
Convex Hull - Chan's Algorithm O(n log h) - Presentation by Yitian Huang and ...
Convex Hull - Chan's Algorithm O(n log h) - Presentation by Yitian Huang and ...Convex Hull - Chan's Algorithm O(n log h) - Presentation by Yitian Huang and ...
Convex Hull - Chan's Algorithm O(n log h) - Presentation by Yitian Huang and ...
 
Dynamic Programming - Part II
Dynamic Programming - Part IIDynamic Programming - Part II
Dynamic Programming - Part II
 
Solving Problems with Graphs
Solving Problems with GraphsSolving Problems with Graphs
Solving Problems with Graphs
 
NP completeness
NP completenessNP completeness
NP completeness
 
Dynamic Programming - Part 1
Dynamic Programming - Part 1Dynamic Programming - Part 1
Dynamic Programming - Part 1
 
Online algorithms in Machine Learning
Online algorithms in Machine LearningOnline algorithms in Machine Learning
Online algorithms in Machine Learning
 
Graph Traversal Algorithms - Depth First Search Traversal
Graph Traversal Algorithms - Depth First Search TraversalGraph Traversal Algorithms - Depth First Search Traversal
Graph Traversal Algorithms - Depth First Search Traversal
 
Matrix Representation Of Graph
Matrix Representation Of GraphMatrix Representation Of Graph
Matrix Representation Of Graph
 

Similaire à Graphs, Trees, Paths and Their Representations

Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashing
Victor Palmar
 
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
zukun
 
Spanning Tree in data structure and .pptx
Spanning Tree in data structure and .pptxSpanning Tree in data structure and .pptx
Spanning Tree in data structure and .pptx
asimshahzad8611
 

Similaire à Graphs, Trees, Paths and Their Representations (20)

UNIT 4_DSA_KAVITHA_RMP.ppt
UNIT 4_DSA_KAVITHA_RMP.pptUNIT 4_DSA_KAVITHA_RMP.ppt
UNIT 4_DSA_KAVITHA_RMP.ppt
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptx
 
Tries - Tree Based Structures for Strings
Tries - Tree Based Structures for StringsTries - Tree Based Structures for Strings
Tries - Tree Based Structures for Strings
 
Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashing
 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
 
data structures and algorithms Unit 2
data structures and algorithms Unit 2data structures and algorithms Unit 2
data structures and algorithms Unit 2
 
Set Operations - Union Find and Bloom Filters
Set Operations - Union Find and Bloom FiltersSet Operations - Union Find and Bloom Filters
Set Operations - Union Find and Bloom Filters
 
Splay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data StructuresSplay Trees and Self Organizing Data Structures
Splay Trees and Self Organizing Data Structures
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Graphs data structures
Graphs data structuresGraphs data structures
Graphs data structures
 
Graph in data structures
Graph in data structuresGraph in data structures
Graph in data structures
 
Dijkstra
DijkstraDijkstra
Dijkstra
 
d
dd
d
 
Graph clustering
Graph clusteringGraph clustering
Graph clustering
 
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
 
Chapter9 graph data structure
Chapter9  graph data structureChapter9  graph data structure
Chapter9 graph data structure
 
26 spanning
26 spanning26 spanning
26 spanning
 
Binary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red BlackBinary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red Black
 
Start From A MapReduce Graph Pattern-recognize Algorithm
Start From A MapReduce Graph Pattern-recognize AlgorithmStart From A MapReduce Graph Pattern-recognize Algorithm
Start From A MapReduce Graph Pattern-recognize Algorithm
 
Spanning Tree in data structure and .pptx
Spanning Tree in data structure and .pptxSpanning Tree in data structure and .pptx
Spanning Tree in data structure and .pptx
 

Plus de Amrinder Arora

Plus de Amrinder Arora (17)

NP-Completeness - II
NP-Completeness - IINP-Completeness - II
NP-Completeness - II
 
Graph Traversal Algorithms - Breadth First Search
Graph Traversal Algorithms - Breadth First SearchGraph Traversal Algorithms - Breadth First Search
Graph Traversal Algorithms - Breadth First Search
 
Bron Kerbosch Algorithm - Presentation by Jun Zhai, Tianhang Qiang and Yizhen...
Bron Kerbosch Algorithm - Presentation by Jun Zhai, Tianhang Qiang and Yizhen...Bron Kerbosch Algorithm - Presentation by Jun Zhai, Tianhang Qiang and Yizhen...
Bron Kerbosch Algorithm - Presentation by Jun Zhai, Tianhang Qiang and Yizhen...
 
Arima Forecasting - Presentation by Sera Cresta, Nora Alosaimi and Puneet Mahana
Arima Forecasting - Presentation by Sera Cresta, Nora Alosaimi and Puneet MahanaArima Forecasting - Presentation by Sera Cresta, Nora Alosaimi and Puneet Mahana
Arima Forecasting - Presentation by Sera Cresta, Nora Alosaimi and Puneet Mahana
 
Stopping Rule for Secretory Problem - Presentation by Haoyang Tian, Wesam Als...
Stopping Rule for Secretory Problem - Presentation by Haoyang Tian, Wesam Als...Stopping Rule for Secretory Problem - Presentation by Haoyang Tian, Wesam Als...
Stopping Rule for Secretory Problem - Presentation by Haoyang Tian, Wesam Als...
 
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
Proof of O(log *n) time complexity of Union find (Presentation by Wei Li, Zeh...
 
Proof of Cook Levin Theorem (Presentation by Xiechuan, Song and Shuo)
Proof of Cook Levin Theorem (Presentation by Xiechuan, Song and Shuo)Proof of Cook Levin Theorem (Presentation by Xiechuan, Song and Shuo)
Proof of Cook Levin Theorem (Presentation by Xiechuan, Song and Shuo)
 
Greedy Algorithms
Greedy AlgorithmsGreedy Algorithms
Greedy Algorithms
 
Divide and Conquer - Part II - Quickselect and Closest Pair of Points
Divide and Conquer - Part II - Quickselect and Closest Pair of PointsDivide and Conquer - Part II - Quickselect and Closest Pair of Points
Divide and Conquer - Part II - Quickselect and Closest Pair of Points
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Introduction to Algorithms and Asymptotic Notation
Introduction to Algorithms and Asymptotic NotationIntroduction to Algorithms and Asymptotic Notation
Introduction to Algorithms and Asymptotic Notation
 
Binomial Heaps and Fibonacci Heaps
Binomial Heaps and Fibonacci HeapsBinomial Heaps and Fibonacci Heaps
Binomial Heaps and Fibonacci Heaps
 
R-Trees and Geospatial Data Structures
R-Trees and Geospatial Data StructuresR-Trees and Geospatial Data Structures
R-Trees and Geospatial Data Structures
 
BTrees - Great alternative to Red Black, AVL and other BSTs
BTrees - Great alternative to Red Black, AVL and other BSTsBTrees - Great alternative to Red Black, AVL and other BSTs
BTrees - Great alternative to Red Black, AVL and other BSTs
 
Stacks, Queues, Binary Search Trees - Lecture 1 - Advanced Data Structures
Stacks, Queues, Binary Search Trees -  Lecture 1 - Advanced Data StructuresStacks, Queues, Binary Search Trees -  Lecture 1 - Advanced Data Structures
Stacks, Queues, Binary Search Trees - Lecture 1 - Advanced Data Structures
 
Online Algorithms - An Introduction
Online Algorithms - An IntroductionOnline Algorithms - An Introduction
Online Algorithms - An Introduction
 
Learning to learn
Learning to learnLearning to learn
Learning to learn
 

Dernier

Dernier (20)

Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 

Graphs, Trees, Paths and Their Representations

  • 1. CS 6213 – Advanced Data Structures Lecture 2 GRAPHS AND THEIR REPRESENTATION TREES, PATHS, CYCLES TOPOLOGICAL SORTING
  • 2.  Instructor Prof. Amrinder Arora amrinder@gwu.edu Please copy TA on emails Please feel free to call as well  TA Iswarya Parupudi iswarya2291@gwmail.gwu.edu CS 6213 – Arora – L2 Advanced Data Structures - Graphs 2 LOGISTICS
  • 3. L4 - BTrees CS 6213 - Advanced Data Structures - Arora 3 CS 6213 Basics Record / Struct Arrays / Linked Lists / Stacks / Queues Graphs / Trees / BSTs Advanced Trie, B-Tree Splay Trees R-Trees Heaps and PQs Union Find
  • 4.  Graphs – Basics  Degrees, Number of Edges, Min/Max Degree  Kinds of Graphs  How to Represent in Data Structures  Trees, Paths, Cycles  Journeys  Topological Sorting, DAGs CS 6213 – Arora – L2 Advanced Data Structures - Graphs 4 AGENDA
  • 5.  A graph G=(V,E) consists of a finite set V, which is the set of vertices, and set E, which is the set of edges. Each edge in E connects two vertices v1 and v2, which are in V.  Can be directed or undirected Not to be confused with a bar graph!!!!  CS 6213 – Arora – L2 Advanced Data Structures - Graphs 5 GRAPH
  • 6. A core data structure that shows up in many circumstances:  Transportation and Logistics (paths, etc.)  Circuit Design  Social Networking – Model connections between people  Sociology – Model influence  Zoology and Wildlife  Project Task Management  Job Scheduling and Resource Assignment (matching)  Time table scheduling  Task parallelization (graph coloring) CS 6213 – Arora – L2 Advanced Data Structures - Graphs 6 GRAPH – APPLICATIONS
  • 7.  (Undirected) Degree of a node  (Directed) Indegree / Outdegree  Min degree in a graph:   Max degree in a graph:   Basic observations  (Undirected) Sum of degrees = 2 x number of edges  (Directed) Sum of indegree = Sum of outdegree = number of edges CS 6213 – Arora – L2 Advanced Data Structures - Graphs 7 DEGREE
  • 8.  If (x,y) is an edge, then x is said to be adjacent to y, and y is adjacent from x.  In the case of undirected graphs, if (x,y) is an edge, we just say that x and y are adjacent (or x is adjacent to y, or y is adjacent to x). Also, we say that x is the neighbor of y.  The indegree of a node x is the number of nodes adjacent to x  The outdegree of a node x is the number of nodes adjacent from x  The degree of a node x in an undirected graph is the number of neighbors of x  A path from a node x to a node y in a graph is a sequence of node x, x1,x2,...,xn,y, such that x is adjacent to x1, x1 is adjacent to x2, ..., and xn is adjacent to y.  The length of a path is the number of its edges.  A cycle is a path that begins and ends at the same node  The distance from node x to node y is the length of the shortest path from x to y. CS 6213 – Arora – L2 Advanced Data Structures - Graphs 8 GRAPH DEFINITIONS
  • 9.  Using a matrix A[1..n,1..n] where A[i,j] = 1 if (i,j) is an edge, and is 0 otherwise. This representation is called the adjacency matrix representation. If the graph is undirected, then the adjacency matrix is symmetric about the main diagonal.  Using an array Adj[1..n] of pointers, which Adj[i] is a linked list of nodes which are adjacent to i.  The matrix representation requires more memory, since it has a matrix cell for each possible edge, whether that edge exists or not. In adjacency list representation, the space used is directly proportional to the number of edges.  If the graph is sparse (very few edges), then adjacency list may be a more efficient choice. CS 6213 – Arora – L2 Advanced Data Structures - Graphs 9 GRAPH REPRESENTATIONS
  • 10.  A very practical choice is to use graphing libraries, such as:  JGraphT (Java)  Boost (C++)  GraphStream (Java)  JUNG (Java) CS 6213 – Arora – L2 Advanced Data Structures - Graphs 10 GRAPH REPRESENTATION (CONT.)
  • 11.  Graphs can be characterized in many ways. Two important ones being:  Directed or Undirected  Weighted or Unweighted  Both Adjacency Matrix (AM) and Adjacency List (AL) representations can be used for graphs – weighted or unweighted, directed or undirected.  A[i,j] = A[j,i] if graph is undirected. So, we could decide to use just the upper triangle.  If graph is weighted, in adjacency list, we can also store the weight. AL[i] = [(j,w(i,j)), (k,w(i,k)), …] CS 6213 – Arora – L2 Advanced Data Structures - Graphs 11 GRAPH CHARACTERIZATIONS
  • 12.  A tree is a connected acyclic graph (i.e., it has no cycles)  Rooted tree: A tree in which one node is designated as a root (the top node) CS 6213 – Arora – L2 Advanced Data Structures - Graphs 12 TREE Example: Node A is root node F and D are child nodes of A. P and Q are child nodes of J. Etc.
  • 13.  Definitions  Leaf is a node that has no children  Ancestors of a node x are all the nodes on the path from x to the root, including x and the root  Subtree rooted at x is the tree consisting of x, its children and their children, and so on and so forth all the way down  Height of a tree is the maximum distance from the root to any node CS 6213 – Arora – L2 Advanced Data Structures - Graphs 13 TREE (CONT.)
  • 14. Option 1 •Trees are graphs, so we can use standard graph representation – Adjacency Matrix or Adjacency List Option 2 •Use parent node and list for child nodes Option 3 •Use parent node, and two pointers – one for first child and the other for nextSibling CS 6213 – Arora – L2 Advanced Data Structures - Graphs 14 REPRESENTING TREES 3 Basic Options
  • 15.  We can use standard graph representation – Adjacency Matrix or Adjacency List  These options are overkill for trees, but in some instances, the graph is not known to be a tree beforehand, so this option works. CS 6213 – Arora – L2 Advanced Data Structures - Graphs 15 TREE REPRESENTATION – OPTION 1
  • 16.  Rather than using Adjacency Matrix or Adjacency List representation, we can use a simpler representation  Each node has a pointer to parent, and a linked list of child nodes  The root node’s parent pointer is null  This representation works for “rooted” trees. If the tree is not rooted, we can designate one node as root. CS 6213 – Arora – L2 Advanced Data Structures - Graphs 16 TREE REPRESENTATION – OPTION 2 Node { Node parent, List<Node> childNodes }
  • 17.  Another representation for Trees: Left Child, Right Sibling representation for a tree. Each node has 3 pointers:  Parent – Points to parent (null if this is the root node)  Left pointer – Points to first child (null if this is a leaf node)  Right pointer – Points to right sibling (null if no more siblings)  For example:  is represented by CS 6213 – Arora – L2 Advanced Data Structures - Graphs 17 TREE REPRESENTATION – OPTION 3 Node { Node parent, Node firstChild, Node nextSibling }
  • 18.  When updating values in a tree, such as the size of the subtree rooted at a node, the weight of the subtree rooted at a node, etc, there are two main methods:  Recompute whenever there is a modify operation (addition of a node, deletion of a node, changing the weight of a node, etc). Recomputations usually only need to propagate from the change node upwards to the root. [Advantage: Values always up to date, Disadvantages: Lot of time spent in Recompute, Method cannot be run concurrently.]  Use a dirty flag and set to true when there is a change. Set dirty flag to true for all ancestors (navigate to parent, until the root). Recompute when there is a need, or as per a schedule. [Advantages: Efficient, Methods (other than the “recomputed” operation can be run concurrently. Disadvantages: Values are out of date at times.] CS 6213 – Arora – L2 Advanced Data Structures - Graphs 18 UPDATING VALUES
  • 19.  Able to hold the entire graph in memory?  If your graph is large and changing fast, like the Facebook interconnection graph, you simply cannot hold it in memory using traditional methods. You need to replicate it across multiple servers and use reliable services to get partial data out from the graph. Your graph may simply be backed by a database with which you interact directly (without ever loading a complete “graph” object.) CS 6213 – Arora – L2 Advanced Data Structures - Graphs 19 LARGE GRAPHS
  • 20.  Given each of the graph representations, how do we find a path?  Shortest path algorithms  Dijkstra  All Pairs Shortest Paths  [Refer to CS 6212 Notes for details] CS 6213 – Arora – L2 Advanced Data Structures - Graphs 20 PATHS
  • 21.  Path, spread over time  Useful concept if the graph changes over time  Specifically, consider this scenario:  Edge e1 existed from x to y at time t1  Edge e2 existed from y to z at time t2  t1 < t2  Then, we say that there exists a journey from x to z CS 6213 – Arora – L2 Advanced Data Structures - Graphs 21 JOURNEY
  • 22.  How can we detect cycles in a graph? CS 6213 – Arora – L2 Advanced Data Structures - Graphs 22 CYCLES
  • 23.  Assuming a graph is a Directed Acyclic Graph, topological ordering can be produced in linear time. O(n + m) CS 6213 – Arora – L2 Advanced Data Structures - Graphs 23 TOPOLOGICAL SORTING
  • 24.  Graphs are important data structures with numerous applications  Graphs can be of different kinds  Many convenient ways to model graphs  Adjacency Matrix  Adjacency List  Special structures for trees  Many commercial and open source libraries exist, such as JGraphT CS 6213 – Arora – L2 Advanced Data Structures - Graphs 24 SUMMARY