SlideShare ist ein Scribd-Unternehmen logo
1 von 69
Downloaden Sie, um offline zu lesen
Representing and visiting graphs
Tecniche di Programmazione – A.A. 2012/2013
Summary
A.A. 2012/2013Tecniche di programmazione2
 Graph representation
 The JGraphT library
 Graph visits
 Visits in JGraphT
Graph representation
Representing and visiting graphs
Representing graphs
List structures Matrix structures
A.A. 2012/2013Tecniche di programmazione4
 Adjacency list
 Each vertex has a list of which
vertices it is adjacent to.
 For undirected graphs,
information is duplicated
 Incidence list
 Each vertex has a list of ‘edge’
objects
 Edges are represented by a
pair (a tuple if directed) of
vertices (that the edge
connects) and possibly weight
and other data.
 Adjacency matrix
 A = |V| x |V| matrix of
Booleans or integers
 If there is an edge from a
vertex v to a vertex v’, then the
element A[v,v’] is 1, otherwise
0.
 Incidence matrix
 IM = |V| x |E| matrix of integers
 IM[v,e] = 1 (incident), 0 (not
incident)
 For directed graphs, may be -1
(out) and +1 (in)
Example
A.A. 2012/2013Tecniche di programmazione5
Adjacency
matrix
Adjacency
list
Adjacency list (undirected graph)
A.A. 2012/2013Tecniche di programmazione6
5
1
4
2
3
1
2
3
4
5
2 5
1 5 3 4
2 4
5 2 3
1 2 4
Adjacency list (undirected graph)
A.A. 2012/2013Tecniche di programmazione7
5
1
4
2
3
1
2
3
4
5
2 5
1 5 3 4
2 4
5 2 3
1 2 4
Undirected ==>
All edges are
represented twice
Adjacency list (un-connected graph)
A.A. 2012/2013Tecniche di programmazione8
Un-connected graph,
same rules
Adjacency list (directed graph)
A.A. 2012/2013Tecniche di programmazione9
5
1
4
2
3
1
2
3
4
5
2
3 4
3
5
1 2
Adjacency list
A.A. 2012/2013Tecniche di programmazione10
Adjacency matrix (undirected graph)
A.A. 2012/2013Tecniche di programmazione11
1 2 3 4 5
1 0 1 0 0 1
2 1 0 1 1 1
3 0 1 0 1 0
4 0 1 1 0 1
5 1 1 0 1 0
5
1
4
2
3
Undirected =>
symmetric matrix
No self-loops: zero
diagonal
Adjacency matrix (undirected graph)
A.A. 2012/2013Tecniche di programmazione12
1 2 3 4 5
1 1 0 0 1
2 1 1 1
3 1 0
4 1
5
5
1
4
2
3
Undirected =>
symmetric matrix
50% of memory can
be saved
Adjacency matrix (directed graph)
A.A. 2012/2013Tecniche di programmazione13
1 2 3 4 5
1 0 1 0 0 0
2 0 0 1 1 0
3 0 0 1 0 0
0 0 0 0 1
1 1 0 0 0
5
1
4
2
3
4
5
From-vertex
(out-edges)
To-vertex
(in-edges)
Self-loops in the
diagonal
Adjacency matrix (weighted graph)
A.A. 2012/2013Tecniche di programmazione14
1 2 3 4 5
1 0 2 0 0 0
2 0 0 3 5 0
3 0 0 1 0 0
0 0 0 0 2
1 3 0 0 0
5
1
4
2
3
4
5
Values = edge weight
2
3
1
2
5
1
3
Adjacency matrix
A.A. 2012/2013Tecniche di programmazione15
Incidence matrix (undirected graph)
A.A. 2012/2013Tecniche di programmazione16
1 2 3 4 5
1 1 1 0 0 0
2 1 0 1 1 0
3 0 0 0 0 0
4 0 0 0 1 1
5 0 1 1 0 1
v5
v1
v4
v2
v3
Edges e1…e7
e1
e2 e3 e4
e5
e6
e7
6
0
1
1
0
0
7
0
0
1
1
0
Vertices
v1…v5
Exactly 2 “ones”
in every column
# of “ones” in a
row = vertex
degree
Incidence matrix (directed graph)
A.A. 2012/2013Tecniche di programmazione17
v5
v1
v4
v2
v3
e1
e2 e3 e4
e5
e6
e7
1 2 3 4 5
1 -1 +1 0 0 0
2 +1 0 +1 -1 0
3 0 0 0 0 0
4 0 0 0 +1 -1
5 0 -1 -1 0 +1
Edges e1…e7
6
0
-1
+1
0
0
7
0
0
-1
+1
0
Vertices
v1…v5
Self loops can’t
be represented
-1: exit
+1: enter
indegree =
count(+1)
outdegree =
count(-1)
Complexity & trade-offs
A.A. 2012/2013Tecniche di programmazione18
Adjacency List Adjacency Matrix Incidence Matrix
Space O( |V| + |E| ) O( |V| x |V| ) O( |V| x |E| )
Space For sparse graphs
|E| << |V|2
For dense graphs
|E| ~ |V|2
Check edge O(1+deg(v)) O(1) O(|E|) if v,v’ are
known, or
O(1) if e is known
Find all adjacent O(1+deg(v)) O(|V|) O(|V|+|E|)
The JGraphT library
Representing and visiting graphs
JGraphT
A.A. 2012/2013Tecniche di programmazione20
 http://jgrapht.org
 (do not confuse with
jgraph.com)
 Free Java graph library
that provides graph
objects and algorithms
 Easy, type-safe and
extensible thanks to
<generics>
 Just add jgrapht-
jdk1.6.jar to your
project
JGraphT structure
A.A. 2012/2013Tecniche di programmazione21
Packages
org.jgrapht
The front-end API's interfaces and classes,
including Graph, DirectedGraph and UndirectedGraph.
org.jgrapht.alg Algorithms provided with JGraphT.
org.jgrapht.alg.util Utilities used by JGraphT algorithms.
org.jgrapht.demo Demo programs that help to get started with JGraphT.
org.jgrapht.event
Event classes and listener interfaces, used to provide a change
notification mechanism on graph modification events.
org.jgrapht.ext Extensions and integration means to other products.
org.jgrapht.generate Generators for graphs of various topologies.
org.jgrapht.graph Implementations of various graphs.
org.jgrapht.traverse Graph traversal means.
org.jgrapht.util
Non-graph-specific data structures, algorithms, and utilities
used by JGraphT.
Graph objects
A.A. 2012/2013Tecniche di programmazione22
 All graphs derive from
 Interface Graph<V,E>
 V = type of vertices
 E = type of edges
 usually DefaultEdge or DefaultWeightedEdge
 Main interfaces
 DirectedGraph<V,E>
 UndirectedGraph<V,E>
 WeightedGraph<V,E>
JGraphT main interfaces
A.A. 2012/2013Tecniche di programmazione23
Graph classes
A.A. 2012/2013Tecniche di programmazione24
Graph
DirectedGraph UndirectedGraph WeightedGraph
I
I
I I
DefaultDirectedGraph
org.jgrapht
org.jgrapht.graphs
DefaultDirectedWeightedGraph
DirectedWeightedMultigraph
DirectedWeightedPseudograph
DirectedMultigraph DirectedPseudograph
Multigraph
Pseudograph
SimpleDirectedGraph
SimpleGraph
SimpleWeightedGraph
SimpleDirectedWeightedGraph
WeightedMultigraph WeightedPseudograph
Graph classes
A.A. 2012/2013Tecniche di programmazione25
Graph classes
A.A. 2012/2013Tecniche di programmazione26
Undirected Directed
Graph classes
A.A. 2012/2013Tecniche di programmazione27
Weighted
Not
weighted
Not
weighted
Graph classes
A.A. 2012/2013Tecniche di programmazione28
Simple
Multi
Pseudo
Non simple (loops allowed, no multi edges)
Creating graphs
A.A. 2012/2013Tecniche di programmazione29
 Construct your desired type of graph
 Add vertices
 boolean addVertex(V v)
 Add edges
 E addEdge(V sourceVertex,V targetVertex)
 boolean addEdge(V sourceVertex,V targetVertex, E e)
 void setEdgeWeight(E e, double weight)
 Print graph (for debugging)
 toString()
 Warning: E andV should correctly implement .equals()
and .hashCode()
Example
A.A. 2012/2013Tecniche di programmazione30
r s t u
v w x y
z
For testing…
A.A. 2012/2013Tecniche di programmazione31
Example
A.A. 2012/2013Tecniche di programmazione32
http://www.sfmtorino.it/le-linee-sfm/
Example
A.A. 2012/2013Tecniche di programmazione33
https://didattica.polito.it/pls/portal30/gap.a_mds
.espandi2?p_a_acc=2013&p_sdu=37&p_cds=3
&p_header=&p_lang=IT
Querying graph structure
A.A. 2012/2013Tecniche di programmazione34
 Navigate structure
 java.util.Set<V> vertexSet()
 boolean containsVertex(V v)
 boolean containsEdge(V sourceVertex,V targetVertex)
 java.util.Set<E> edgesOf(V vertex)
 java.util.Set<E> getAllEdges(V sourceVertex,V targetVertex)
 Query Edges
 V getEdgeSource(E e)
 V getEdgeTarget(E e)
 double getEdgeWeight(E e)
Utility functions
A.A. 2012/2013Tecniche di programmazione35
 Static class org.jgrapht.Graphs
 Easier creation
 public static <V,E> E addEdge(Graph<V,E> g,V sourceVertex,
V targetVertex, double weight)
 public static <V,E> E addEdgeWithVertices(Graph<V,E> g,
V sourceVertex,V targetVertex)
 Easier navigation
 public static <V,E> java.util.List<V>
neighborListOf(Graph<V,E> g,V vertex)
 public static <V,E> java.util.List<V>
predecessorListOf(DirectedGraph<V,E> g,V vertex)
 public static <V,E> java.util.List<V>
successorListOf(DirectedGraph<V,E> g,V vertex)
Graph visits
Representing and visiting graphs
Visit Algorithms
A.A. 2012/2013Tecniche di programmazione37
 Visit =
 Systematic exploration of a graph
 Starting from a ‘source’ vertex
 Reaching all reachable vertices
 Main strategies
 Breadth-first visit (“in ampiezza”)
 Depth-first visit (“in profondità”)
Breadth-First Visit
A.A. 2012/2013Tecniche di programmazione38
 Also called Breadth-first search (BFV or BFS)
 All reachable vertices are visited “by levels”
 L – level of the visit
 SL – set of vertices in level L
 L=0, S0={ vsource }
 Repeat while SL is not empty:
 SL+1 = set of all vertices:
 not visited yet, and
 adjacent to at least one vertex in SL
 L=L+1
Example
A.A. 2012/2013Tecniche di programmazione39
r s t u
v w x y
Source = s
L = 0
S0 = {s}
Example
A.A. 2012/2013Tecniche di programmazione40
r s t u
v w x y
L = 1
S0 = {s}
S1 = {r, w}
Example
A.A. 2012/2013Tecniche di programmazione41
r s t u
v w x y
L = 2
S1 = {r, w}
S2 = {v, t, x}
Example
A.A. 2012/2013Tecniche di programmazione42
r s t u
v w x y
L = 3
S2 = {v, t, x}
S3 = {u, y}
BFS Tree
A.A. 2012/2013Tecniche di programmazione43
 The result of a BFV identifies a “visit tree” in the graph:
 The tree root is the source vertex
 Tree nodes are all graph vertices
 (in the same connected component of the source)
 Tree are a subset of graph edges
 Those edges that have been used to “discover” new vertices.
BFS Tree
A.A. 2012/2013Tecniche di programmazione44
r s t u
v w x y
Minimum (shortest) paths
A.A. 2012/2013Tecniche di programmazione45
 Shortest path: the minumum number of edges on any
path between two vertices
 The BFS procedure computes all minimum paths for all
vertices, starting from the source vertex
 NB: unweighted graph : path length = number of edges
Depth First Visit
A.A. 2012/2013Tecniche di programmazione46
 Also called Breadth-first search (DFV or DFS)
 Opposite approach to BFS
 At every step, visit one (yet unvisited) vertex, adjacent to
the last visited one
 If no such vertex exist, go back one step to the previously
visited vertex
 Lends itself to recursive implementation
 Similar to tree visit procedures
DFS Algorithm
A.A. 2012/2013Tecniche di programmazione47
 DFS(Vertex v)
 For all ( w : adjacent_to(v) )
 If( not visited (w) )
 Visit (w)
 DFS(w)
 Start with: DFS(source)
Example
A.A. 2012/2013Tecniche di programmazione48
r s t u
v w x y
Source = s
Example
A.A. 2012/2013Tecniche di programmazione49
r s t u
v w x y
Source = s
Visit r
Example
A.A. 2012/2013Tecniche di programmazione50
r s t u
v w x y
Source = s
Visit r
Visit v
Example
A.A. 2012/2013Tecniche di programmazione51
r s t u
v w x y
Source = s
Back to r
Back to s
Visit w
Example
A.A. 2012/2013Tecniche di programmazione52
r s t u
v w x y
Source = s
Visit w
Visit t
Example
A.A. 2012/2013Tecniche di programmazione53
r s t u
v w x y
Source = s
Visit w
Visit t
Visit u
Example
A.A. 2012/2013Tecniche di programmazione54
r s t u
v w x y
Source = s
Visit w
Visit t
Visit u
Visit y
Example
A.A. 2012/2013Tecniche di programmazione55
r s t u
v w x y
Source = s
Visit w
Visit t
Visit u
Visit y
Visit x
Example
A.A. 2012/2013Tecniche di programmazione56
r s t u
v w x y
Source = s
Back to y
Back to u
Back to t
Back to w
DFS tree
Back to s = STOP
Edge classification
A.A. 2012/2013Tecniche di programmazione57
 In an directed graph, after a DFS visit, all edges fall in one
of these 4 categories:
 T: Tree edges (belonging to the DFS tree)
 B: Back edges (not in T, and connect a vertex to one of its
ancestors)
 F: Forward edges (not in T and B, and connect a vertex to one
of its descendants)
 C: Cross edges (all remaining edges)
Example
A.A. 2012/2013Tecniche di programmazione58
x
y
w v
z s
u
t
Directed graph
Example
A.A. 2012/2013Tecniche di programmazione59
x
y
w v
z s
u
t
DFS visit
(sources: s, t)
Example
A.A. 2012/2013Tecniche di programmazione60
x
y
w v
z s
u
t
Edge classification
T T
T TTT B BBF
C C C
Cycles
A.A. 2012/2013Tecniche di programmazione61
 Theorem:
 A directed graph is acyclic if and only if a depth-first visit
does not produce any B edge
Complexity
A.A. 2012/2013Tecniche di programmazione62
 Visits have linear complexity in the graph size
 BFS : O(V+E)
 DFS : (V+E)
 N.B. for dense graphs, E = O(V2)
Visits in JGraphT
Representing and visiting graphs
JGraphT and visits
A.A. 2012/2013Tecniche di programmazione64
 Visits are called “traversals”
 Implemented through iterator classes
 Package org.jgrapht.traverse
Graph traversal classes
A.A. 2012/2013Tecniche di programmazione65
Graph iterators
A.A. 2012/2013Tecniche di programmazione66
 Usual hasNext() and next() methods
 May register event listeners to traversal steps
 void addTraversalListener(TraversalListener<V,E> l)
 TraversalListeners may react to:
 Edge traversed
 Vertex traversed
 Vertex finished
 Connected component started
 Connected component finished
Types of traversal iterators
A.A. 2012/2013Tecniche di programmazione67
 BreadthFirstIterator
 DepthFirstIterator
 ClosestFirstIterator
 The metric for closest here is the path length from a start
vertex. Graph.getEdgeWeight(Edge) is summed to calculate
path length. Optionally, path length may be bounded by a finite
radius.
 TopologicalOrderIterator
 A topological sort is a permutation p of the vertices of
a graph such that an edge {i,j} implies that i appears
before j in p. Only directed acyclic graphs can be topologically
sorted.
Resources
A.A. 2012/2013Tecniche di programmazione68
 Open Data Structures (in Java), Pat Morin,
http://opendatastructures.org/
 Algorithms Course Materials, Jeff Erickson,
http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/
 Graphbook - A book on algorithmic graph theory, David
Joyner, MinhVan Nguyen, and David Phillips,
https://code.google.com/p/graphbook/
Licenza d’uso
A.A. 2012/2013Tecniche di programmazione69
 Queste diapositive sono distribuite con licenza Creative Commons
“Attribuzione - Non commerciale - Condividi allo stesso modo (CC
BY-NC-SA)”
 Sei libero:
 di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,
rappresentare, eseguire e recitare quest'opera
 di modificare quest'opera
 Alle seguenti condizioni:
 Attribuzione — Devi attribuire la paternità dell'opera agli autori originali
e in modo tale da non suggerire che essi avallino te o il modo in cui tu
usi l'opera.
 Non commerciale — Non puoi usare quest'opera per fini commerciali.
 Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se la
usi per crearne un'altra, puoi distribuire l'opera risultante solo con una
licenza identica o equivalente a questa.
 http://creativecommons.org/licenses/by-nc-sa/3.0/

Weitere ähnliche Inhalte

Andere mochten auch

Riusabilità dei contenuti ditattici
 Riusabilità dei contenuti ditattici Riusabilità dei contenuti ditattici
Riusabilità dei contenuti ditatticiFulvio Corno
 
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...Fulvio Corno
 
Progetto FreeAble (Handimatica 2008)
Progetto FreeAble (Handimatica 2008)Progetto FreeAble (Handimatica 2008)
Progetto FreeAble (Handimatica 2008)Fulvio Corno
 
Edifici intelligenti: innovazione tecnologica e convergenza degli impianti
Edifici intelligenti: innovazione tecnologica e convergenza degli impiantiEdifici intelligenti: innovazione tecnologica e convergenza degli impianti
Edifici intelligenti: innovazione tecnologica e convergenza degli impiantiFulvio Corno
 
Introduzione alla disabilità
Introduzione alla disabilitàIntroduzione alla disabilità
Introduzione alla disabilitàFulvio Corno
 
Intelligenza ambientale applicata alla casa
Intelligenza ambientale applicata alla casaIntelligenza ambientale applicata alla casa
Intelligenza ambientale applicata alla casaFulvio Corno
 
Multimedialità ed e-learning
 Multimedialità ed e-learning Multimedialità ed e-learning
Multimedialità ed e-learningFulvio Corno
 
La domotica al servizio della persona
La domotica al servizio della personaLa domotica al servizio della persona
La domotica al servizio della personaFulvio Corno
 
Attivare facilmente il Prompt dei comandi in Code::Blocks
Attivare facilmente il Prompt dei comandi in Code::BlocksAttivare facilmente il Prompt dei comandi in Code::Blocks
Attivare facilmente il Prompt dei comandi in Code::BlocksFulvio Corno
 
Una casa a misura di disabile: la domotica al servizio della persona
Una casa a misura di disabile: la domotica al servizio della personaUna casa a misura di disabile: la domotica al servizio della persona
Una casa a misura di disabile: la domotica al servizio della personaFulvio Corno
 
La percezione sensoriale
La percezione sensorialeLa percezione sensoriale
La percezione sensorialeFulvio Corno
 
Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti...
 Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti... Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti...
Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti...Fulvio Corno
 
Linux Kernel, driver e compilazione
Linux Kernel, driver e compilazioneLinux Kernel, driver e compilazione
Linux Kernel, driver e compilazioneFulvio Corno
 
RDF - Resource Description Framework and RDF Schema
RDF - Resource Description Framework and RDF SchemaRDF - Resource Description Framework and RDF Schema
RDF - Resource Description Framework and RDF SchemaFulvio Corno
 
Tecnologie per la disabilità: presentazione del corso
Tecnologie per la disabilità: presentazione del corsoTecnologie per la disabilità: presentazione del corso
Tecnologie per la disabilità: presentazione del corsoFulvio Corno
 
Il Web Semantico applicato agli edifici intelligenti
Il Web Semantico applicato agli edifici intelligentiIl Web Semantico applicato agli edifici intelligenti
Il Web Semantico applicato agli edifici intelligentiFulvio Corno
 
Introduction to Servlets
Introduction to ServletsIntroduction to Servlets
Introduction to ServletsFulvio Corno
 

Andere mochten auch (17)

Riusabilità dei contenuti ditattici
 Riusabilità dei contenuti ditattici Riusabilità dei contenuti ditattici
Riusabilità dei contenuti ditattici
 
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
Componenti dello stack LAMP - PHP, il linguaggio, l'installazione - MySQL, in...
 
Progetto FreeAble (Handimatica 2008)
Progetto FreeAble (Handimatica 2008)Progetto FreeAble (Handimatica 2008)
Progetto FreeAble (Handimatica 2008)
 
Edifici intelligenti: innovazione tecnologica e convergenza degli impianti
Edifici intelligenti: innovazione tecnologica e convergenza degli impiantiEdifici intelligenti: innovazione tecnologica e convergenza degli impianti
Edifici intelligenti: innovazione tecnologica e convergenza degli impianti
 
Introduzione alla disabilità
Introduzione alla disabilitàIntroduzione alla disabilità
Introduzione alla disabilità
 
Intelligenza ambientale applicata alla casa
Intelligenza ambientale applicata alla casaIntelligenza ambientale applicata alla casa
Intelligenza ambientale applicata alla casa
 
Multimedialità ed e-learning
 Multimedialità ed e-learning Multimedialità ed e-learning
Multimedialità ed e-learning
 
La domotica al servizio della persona
La domotica al servizio della personaLa domotica al servizio della persona
La domotica al servizio della persona
 
Attivare facilmente il Prompt dei comandi in Code::Blocks
Attivare facilmente il Prompt dei comandi in Code::BlocksAttivare facilmente il Prompt dei comandi in Code::Blocks
Attivare facilmente il Prompt dei comandi in Code::Blocks
 
Una casa a misura di disabile: la domotica al servizio della persona
Una casa a misura di disabile: la domotica al servizio della personaUna casa a misura di disabile: la domotica al servizio della persona
Una casa a misura di disabile: la domotica al servizio della persona
 
La percezione sensoriale
La percezione sensorialeLa percezione sensoriale
La percezione sensoriale
 
Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti...
 Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti... Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti...
Scripting - Esecuzione condizionale - Costrutti iterativi - Variabili (quoti...
 
Linux Kernel, driver e compilazione
Linux Kernel, driver e compilazioneLinux Kernel, driver e compilazione
Linux Kernel, driver e compilazione
 
RDF - Resource Description Framework and RDF Schema
RDF - Resource Description Framework and RDF SchemaRDF - Resource Description Framework and RDF Schema
RDF - Resource Description Framework and RDF Schema
 
Tecnologie per la disabilità: presentazione del corso
Tecnologie per la disabilità: presentazione del corsoTecnologie per la disabilità: presentazione del corso
Tecnologie per la disabilità: presentazione del corso
 
Il Web Semantico applicato agli edifici intelligenti
Il Web Semantico applicato agli edifici intelligentiIl Web Semantico applicato agli edifici intelligenti
Il Web Semantico applicato agli edifici intelligenti
 
Introduction to Servlets
Introduction to ServletsIntroduction to Servlets
Introduction to Servlets
 

Ähnlich wie Representing and Visiting Graphs in JGraphT

Introduction to Graphs
Introduction to GraphsIntroduction to Graphs
Introduction to GraphsFulvio Corno
 
Social network-analysis-in-python
Social network-analysis-in-pythonSocial network-analysis-in-python
Social network-analysis-in-pythonJoe OntheRocks
 
Semantic Data Management in Graph Databases
Semantic Data Management in Graph DatabasesSemantic Data Management in Graph Databases
Semantic Data Management in Graph DatabasesMaribel Acosta Deibe
 
Topological Sorting
Topological SortingTopological Sorting
Topological SortingShahDhruv21
 
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...ijseajournal
 
Computational complexity
Computational complexityComputational complexity
Computational complexityFulvio Corno
 
Semantic Data Management in Graph Databases: ESWC 2014 Tutorial
Semantic Data Management in Graph Databases: ESWC 2014 TutorialSemantic Data Management in Graph Databases: ESWC 2014 Tutorial
Semantic Data Management in Graph Databases: ESWC 2014 TutorialMaribel Acosta Deibe
 
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...Thejaka Amila Kanewala, Ph.D.
 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAmrinder Arora
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in javaAbinaya B
 
Graph Summarization with Quality Guarantees
Graph Summarization with Quality GuaranteesGraph Summarization with Quality Guarantees
Graph Summarization with Quality GuaranteesTwo Sigma
 
Graphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ programGraphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ programMuhammad Danish Badar
 
Graph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxGraph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxasimshahzad8611
 
Parallel algorithms
Parallel algorithmsParallel algorithms
Parallel algorithmsguest084d20
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxking779879
 

Ähnlich wie Representing and Visiting Graphs in JGraphT (20)

Introduction to Graphs
Introduction to GraphsIntroduction to Graphs
Introduction to Graphs
 
Social network-analysis-in-python
Social network-analysis-in-pythonSocial network-analysis-in-python
Social network-analysis-in-python
 
09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf09_DS_MCA_Graphs.pdf
09_DS_MCA_Graphs.pdf
 
Semantic Data Management in Graph Databases
Semantic Data Management in Graph DatabasesSemantic Data Management in Graph Databases
Semantic Data Management in Graph Databases
 
Topological Sorting
Topological SortingTopological Sorting
Topological Sorting
 
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
JAVA BASED VISUALIZATION AND ANIMATION FOR TEACHING THE DIJKSTRA SHORTEST PAT...
 
HalifaxNGGs
HalifaxNGGsHalifaxNGGs
HalifaxNGGs
 
Computational complexity
Computational complexityComputational complexity
Computational complexity
 
Semantic Data Management in Graph Databases: ESWC 2014 Tutorial
Semantic Data Management in Graph Databases: ESWC 2014 TutorialSemantic Data Management in Graph Databases: ESWC 2014 Tutorial
Semantic Data Management in Graph Databases: ESWC 2014 Tutorial
 
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
 
PCA and SVD in brief
PCA and SVD in briefPCA and SVD in brief
PCA and SVD in brief
 
Asymptotic Notation and Data Structures
Asymptotic Notation and Data StructuresAsymptotic Notation and Data Structures
Asymptotic Notation and Data Structures
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in java
 
Dijkstra
DijkstraDijkstra
Dijkstra
 
d
dd
d
 
Graph Summarization with Quality Guarantees
Graph Summarization with Quality GuaranteesGraph Summarization with Quality Guarantees
Graph Summarization with Quality Guarantees
 
Graphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ programGraphs and eularian circuit & path with c++ program
Graphs and eularian circuit & path with c++ program
 
Graph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxGraph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptx
 
Parallel algorithms
Parallel algorithmsParallel algorithms
Parallel algorithms
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptx
 

Kürzlich hochgeladen

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 

Kürzlich hochgeladen (20)

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 

Representing and Visiting Graphs in JGraphT

  • 1. Representing and visiting graphs Tecniche di Programmazione – A.A. 2012/2013
  • 2. Summary A.A. 2012/2013Tecniche di programmazione2  Graph representation  The JGraphT library  Graph visits  Visits in JGraphT
  • 4. Representing graphs List structures Matrix structures A.A. 2012/2013Tecniche di programmazione4  Adjacency list  Each vertex has a list of which vertices it is adjacent to.  For undirected graphs, information is duplicated  Incidence list  Each vertex has a list of ‘edge’ objects  Edges are represented by a pair (a tuple if directed) of vertices (that the edge connects) and possibly weight and other data.  Adjacency matrix  A = |V| x |V| matrix of Booleans or integers  If there is an edge from a vertex v to a vertex v’, then the element A[v,v’] is 1, otherwise 0.  Incidence matrix  IM = |V| x |E| matrix of integers  IM[v,e] = 1 (incident), 0 (not incident)  For directed graphs, may be -1 (out) and +1 (in)
  • 5. Example A.A. 2012/2013Tecniche di programmazione5 Adjacency matrix Adjacency list
  • 6. Adjacency list (undirected graph) A.A. 2012/2013Tecniche di programmazione6 5 1 4 2 3 1 2 3 4 5 2 5 1 5 3 4 2 4 5 2 3 1 2 4
  • 7. Adjacency list (undirected graph) A.A. 2012/2013Tecniche di programmazione7 5 1 4 2 3 1 2 3 4 5 2 5 1 5 3 4 2 4 5 2 3 1 2 4 Undirected ==> All edges are represented twice
  • 8. Adjacency list (un-connected graph) A.A. 2012/2013Tecniche di programmazione8 Un-connected graph, same rules
  • 9. Adjacency list (directed graph) A.A. 2012/2013Tecniche di programmazione9 5 1 4 2 3 1 2 3 4 5 2 3 4 3 5 1 2
  • 11. Adjacency matrix (undirected graph) A.A. 2012/2013Tecniche di programmazione11 1 2 3 4 5 1 0 1 0 0 1 2 1 0 1 1 1 3 0 1 0 1 0 4 0 1 1 0 1 5 1 1 0 1 0 5 1 4 2 3 Undirected => symmetric matrix No self-loops: zero diagonal
  • 12. Adjacency matrix (undirected graph) A.A. 2012/2013Tecniche di programmazione12 1 2 3 4 5 1 1 0 0 1 2 1 1 1 3 1 0 4 1 5 5 1 4 2 3 Undirected => symmetric matrix 50% of memory can be saved
  • 13. Adjacency matrix (directed graph) A.A. 2012/2013Tecniche di programmazione13 1 2 3 4 5 1 0 1 0 0 0 2 0 0 1 1 0 3 0 0 1 0 0 0 0 0 0 1 1 1 0 0 0 5 1 4 2 3 4 5 From-vertex (out-edges) To-vertex (in-edges) Self-loops in the diagonal
  • 14. Adjacency matrix (weighted graph) A.A. 2012/2013Tecniche di programmazione14 1 2 3 4 5 1 0 2 0 0 0 2 0 0 3 5 0 3 0 0 1 0 0 0 0 0 0 2 1 3 0 0 0 5 1 4 2 3 4 5 Values = edge weight 2 3 1 2 5 1 3
  • 16. Incidence matrix (undirected graph) A.A. 2012/2013Tecniche di programmazione16 1 2 3 4 5 1 1 1 0 0 0 2 1 0 1 1 0 3 0 0 0 0 0 4 0 0 0 1 1 5 0 1 1 0 1 v5 v1 v4 v2 v3 Edges e1…e7 e1 e2 e3 e4 e5 e6 e7 6 0 1 1 0 0 7 0 0 1 1 0 Vertices v1…v5 Exactly 2 “ones” in every column # of “ones” in a row = vertex degree
  • 17. Incidence matrix (directed graph) A.A. 2012/2013Tecniche di programmazione17 v5 v1 v4 v2 v3 e1 e2 e3 e4 e5 e6 e7 1 2 3 4 5 1 -1 +1 0 0 0 2 +1 0 +1 -1 0 3 0 0 0 0 0 4 0 0 0 +1 -1 5 0 -1 -1 0 +1 Edges e1…e7 6 0 -1 +1 0 0 7 0 0 -1 +1 0 Vertices v1…v5 Self loops can’t be represented -1: exit +1: enter indegree = count(+1) outdegree = count(-1)
  • 18. Complexity & trade-offs A.A. 2012/2013Tecniche di programmazione18 Adjacency List Adjacency Matrix Incidence Matrix Space O( |V| + |E| ) O( |V| x |V| ) O( |V| x |E| ) Space For sparse graphs |E| << |V|2 For dense graphs |E| ~ |V|2 Check edge O(1+deg(v)) O(1) O(|E|) if v,v’ are known, or O(1) if e is known Find all adjacent O(1+deg(v)) O(|V|) O(|V|+|E|)
  • 19. The JGraphT library Representing and visiting graphs
  • 20. JGraphT A.A. 2012/2013Tecniche di programmazione20  http://jgrapht.org  (do not confuse with jgraph.com)  Free Java graph library that provides graph objects and algorithms  Easy, type-safe and extensible thanks to <generics>  Just add jgrapht- jdk1.6.jar to your project
  • 21. JGraphT structure A.A. 2012/2013Tecniche di programmazione21 Packages org.jgrapht The front-end API's interfaces and classes, including Graph, DirectedGraph and UndirectedGraph. org.jgrapht.alg Algorithms provided with JGraphT. org.jgrapht.alg.util Utilities used by JGraphT algorithms. org.jgrapht.demo Demo programs that help to get started with JGraphT. org.jgrapht.event Event classes and listener interfaces, used to provide a change notification mechanism on graph modification events. org.jgrapht.ext Extensions and integration means to other products. org.jgrapht.generate Generators for graphs of various topologies. org.jgrapht.graph Implementations of various graphs. org.jgrapht.traverse Graph traversal means. org.jgrapht.util Non-graph-specific data structures, algorithms, and utilities used by JGraphT.
  • 22. Graph objects A.A. 2012/2013Tecniche di programmazione22  All graphs derive from  Interface Graph<V,E>  V = type of vertices  E = type of edges  usually DefaultEdge or DefaultWeightedEdge  Main interfaces  DirectedGraph<V,E>  UndirectedGraph<V,E>  WeightedGraph<V,E>
  • 23. JGraphT main interfaces A.A. 2012/2013Tecniche di programmazione23
  • 24. Graph classes A.A. 2012/2013Tecniche di programmazione24 Graph DirectedGraph UndirectedGraph WeightedGraph I I I I DefaultDirectedGraph org.jgrapht org.jgrapht.graphs DefaultDirectedWeightedGraph DirectedWeightedMultigraph DirectedWeightedPseudograph DirectedMultigraph DirectedPseudograph Multigraph Pseudograph SimpleDirectedGraph SimpleGraph SimpleWeightedGraph SimpleDirectedWeightedGraph WeightedMultigraph WeightedPseudograph
  • 26. Graph classes A.A. 2012/2013Tecniche di programmazione26 Undirected Directed
  • 27. Graph classes A.A. 2012/2013Tecniche di programmazione27 Weighted Not weighted Not weighted
  • 28. Graph classes A.A. 2012/2013Tecniche di programmazione28 Simple Multi Pseudo Non simple (loops allowed, no multi edges)
  • 29. Creating graphs A.A. 2012/2013Tecniche di programmazione29  Construct your desired type of graph  Add vertices  boolean addVertex(V v)  Add edges  E addEdge(V sourceVertex,V targetVertex)  boolean addEdge(V sourceVertex,V targetVertex, E e)  void setEdgeWeight(E e, double weight)  Print graph (for debugging)  toString()  Warning: E andV should correctly implement .equals() and .hashCode()
  • 30. Example A.A. 2012/2013Tecniche di programmazione30 r s t u v w x y z
  • 32. Example A.A. 2012/2013Tecniche di programmazione32 http://www.sfmtorino.it/le-linee-sfm/
  • 33. Example A.A. 2012/2013Tecniche di programmazione33 https://didattica.polito.it/pls/portal30/gap.a_mds .espandi2?p_a_acc=2013&p_sdu=37&p_cds=3 &p_header=&p_lang=IT
  • 34. Querying graph structure A.A. 2012/2013Tecniche di programmazione34  Navigate structure  java.util.Set<V> vertexSet()  boolean containsVertex(V v)  boolean containsEdge(V sourceVertex,V targetVertex)  java.util.Set<E> edgesOf(V vertex)  java.util.Set<E> getAllEdges(V sourceVertex,V targetVertex)  Query Edges  V getEdgeSource(E e)  V getEdgeTarget(E e)  double getEdgeWeight(E e)
  • 35. Utility functions A.A. 2012/2013Tecniche di programmazione35  Static class org.jgrapht.Graphs  Easier creation  public static <V,E> E addEdge(Graph<V,E> g,V sourceVertex, V targetVertex, double weight)  public static <V,E> E addEdgeWithVertices(Graph<V,E> g, V sourceVertex,V targetVertex)  Easier navigation  public static <V,E> java.util.List<V> neighborListOf(Graph<V,E> g,V vertex)  public static <V,E> java.util.List<V> predecessorListOf(DirectedGraph<V,E> g,V vertex)  public static <V,E> java.util.List<V> successorListOf(DirectedGraph<V,E> g,V vertex)
  • 36. Graph visits Representing and visiting graphs
  • 37. Visit Algorithms A.A. 2012/2013Tecniche di programmazione37  Visit =  Systematic exploration of a graph  Starting from a ‘source’ vertex  Reaching all reachable vertices  Main strategies  Breadth-first visit (“in ampiezza”)  Depth-first visit (“in profondità”)
  • 38. Breadth-First Visit A.A. 2012/2013Tecniche di programmazione38  Also called Breadth-first search (BFV or BFS)  All reachable vertices are visited “by levels”  L – level of the visit  SL – set of vertices in level L  L=0, S0={ vsource }  Repeat while SL is not empty:  SL+1 = set of all vertices:  not visited yet, and  adjacent to at least one vertex in SL  L=L+1
  • 39. Example A.A. 2012/2013Tecniche di programmazione39 r s t u v w x y Source = s L = 0 S0 = {s}
  • 40. Example A.A. 2012/2013Tecniche di programmazione40 r s t u v w x y L = 1 S0 = {s} S1 = {r, w}
  • 41. Example A.A. 2012/2013Tecniche di programmazione41 r s t u v w x y L = 2 S1 = {r, w} S2 = {v, t, x}
  • 42. Example A.A. 2012/2013Tecniche di programmazione42 r s t u v w x y L = 3 S2 = {v, t, x} S3 = {u, y}
  • 43. BFS Tree A.A. 2012/2013Tecniche di programmazione43  The result of a BFV identifies a “visit tree” in the graph:  The tree root is the source vertex  Tree nodes are all graph vertices  (in the same connected component of the source)  Tree are a subset of graph edges  Those edges that have been used to “discover” new vertices.
  • 44. BFS Tree A.A. 2012/2013Tecniche di programmazione44 r s t u v w x y
  • 45. Minimum (shortest) paths A.A. 2012/2013Tecniche di programmazione45  Shortest path: the minumum number of edges on any path between two vertices  The BFS procedure computes all minimum paths for all vertices, starting from the source vertex  NB: unweighted graph : path length = number of edges
  • 46. Depth First Visit A.A. 2012/2013Tecniche di programmazione46  Also called Breadth-first search (DFV or DFS)  Opposite approach to BFS  At every step, visit one (yet unvisited) vertex, adjacent to the last visited one  If no such vertex exist, go back one step to the previously visited vertex  Lends itself to recursive implementation  Similar to tree visit procedures
  • 47. DFS Algorithm A.A. 2012/2013Tecniche di programmazione47  DFS(Vertex v)  For all ( w : adjacent_to(v) )  If( not visited (w) )  Visit (w)  DFS(w)  Start with: DFS(source)
  • 48. Example A.A. 2012/2013Tecniche di programmazione48 r s t u v w x y Source = s
  • 49. Example A.A. 2012/2013Tecniche di programmazione49 r s t u v w x y Source = s Visit r
  • 50. Example A.A. 2012/2013Tecniche di programmazione50 r s t u v w x y Source = s Visit r Visit v
  • 51. Example A.A. 2012/2013Tecniche di programmazione51 r s t u v w x y Source = s Back to r Back to s Visit w
  • 52. Example A.A. 2012/2013Tecniche di programmazione52 r s t u v w x y Source = s Visit w Visit t
  • 53. Example A.A. 2012/2013Tecniche di programmazione53 r s t u v w x y Source = s Visit w Visit t Visit u
  • 54. Example A.A. 2012/2013Tecniche di programmazione54 r s t u v w x y Source = s Visit w Visit t Visit u Visit y
  • 55. Example A.A. 2012/2013Tecniche di programmazione55 r s t u v w x y Source = s Visit w Visit t Visit u Visit y Visit x
  • 56. Example A.A. 2012/2013Tecniche di programmazione56 r s t u v w x y Source = s Back to y Back to u Back to t Back to w DFS tree Back to s = STOP
  • 57. Edge classification A.A. 2012/2013Tecniche di programmazione57  In an directed graph, after a DFS visit, all edges fall in one of these 4 categories:  T: Tree edges (belonging to the DFS tree)  B: Back edges (not in T, and connect a vertex to one of its ancestors)  F: Forward edges (not in T and B, and connect a vertex to one of its descendants)  C: Cross edges (all remaining edges)
  • 58. Example A.A. 2012/2013Tecniche di programmazione58 x y w v z s u t Directed graph
  • 59. Example A.A. 2012/2013Tecniche di programmazione59 x y w v z s u t DFS visit (sources: s, t)
  • 60. Example A.A. 2012/2013Tecniche di programmazione60 x y w v z s u t Edge classification T T T TTT B BBF C C C
  • 61. Cycles A.A. 2012/2013Tecniche di programmazione61  Theorem:  A directed graph is acyclic if and only if a depth-first visit does not produce any B edge
  • 62. Complexity A.A. 2012/2013Tecniche di programmazione62  Visits have linear complexity in the graph size  BFS : O(V+E)  DFS : (V+E)  N.B. for dense graphs, E = O(V2)
  • 63. Visits in JGraphT Representing and visiting graphs
  • 64. JGraphT and visits A.A. 2012/2013Tecniche di programmazione64  Visits are called “traversals”  Implemented through iterator classes  Package org.jgrapht.traverse
  • 65. Graph traversal classes A.A. 2012/2013Tecniche di programmazione65
  • 66. Graph iterators A.A. 2012/2013Tecniche di programmazione66  Usual hasNext() and next() methods  May register event listeners to traversal steps  void addTraversalListener(TraversalListener<V,E> l)  TraversalListeners may react to:  Edge traversed  Vertex traversed  Vertex finished  Connected component started  Connected component finished
  • 67. Types of traversal iterators A.A. 2012/2013Tecniche di programmazione67  BreadthFirstIterator  DepthFirstIterator  ClosestFirstIterator  The metric for closest here is the path length from a start vertex. Graph.getEdgeWeight(Edge) is summed to calculate path length. Optionally, path length may be bounded by a finite radius.  TopologicalOrderIterator  A topological sort is a permutation p of the vertices of a graph such that an edge {i,j} implies that i appears before j in p. Only directed acyclic graphs can be topologically sorted.
  • 68. Resources A.A. 2012/2013Tecniche di programmazione68  Open Data Structures (in Java), Pat Morin, http://opendatastructures.org/  Algorithms Course Materials, Jeff Erickson, http://www.cs.uiuc.edu/~jeffe/teaching/algorithms/  Graphbook - A book on algorithmic graph theory, David Joyner, MinhVan Nguyen, and David Phillips, https://code.google.com/p/graphbook/
  • 69. Licenza d’uso A.A. 2012/2013Tecniche di programmazione69  Queste diapositive sono distribuite con licenza Creative Commons “Attribuzione - Non commerciale - Condividi allo stesso modo (CC BY-NC-SA)”  Sei libero:  di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico, rappresentare, eseguire e recitare quest'opera  di modificare quest'opera  Alle seguenti condizioni:  Attribuzione — Devi attribuire la paternità dell'opera agli autori originali e in modo tale da non suggerire che essi avallino te o il modo in cui tu usi l'opera.  Non commerciale — Non puoi usare quest'opera per fini commerciali.  Condividi allo stesso modo — Se alteri o trasformi quest'opera, o se la usi per crearne un'altra, puoi distribuire l'opera risultante solo con una licenza identica o equivalente a questa.  http://creativecommons.org/licenses/by-nc-sa/3.0/