Representing and visiting graphs


Published on

Graphs: representations and visits

Graph representation
The JGraphT library
Graph visits
Visits in JGraphT

Teaching material for the course of "Tecniche di Programmazione" at Politecnico di Torino in year 2012/2013. More information:

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Representing and visiting graphs

  1. 1. Representing and visiting graphsTecniche di Programmazione – A.A. 2012/2013
  2. 2. SummaryA.A. 2012/2013Tecniche di programmazione2 Graph representation The JGraphT library Graph visits Visits in JGraphT
  3. 3. Graph representationRepresenting and visiting graphs
  4. 4. Representing graphsList structures Matrix structuresA.A. 2012/2013Tecniche di programmazione4 Adjacency list Each vertex has a list of whichvertices it is adjacent to. For undirected graphs,information is duplicated Incidence list Each vertex has a list of ‘edge’objects Edges are represented by apair (a tuple if directed) ofvertices (that the edgeconnects) and possibly weightand other data. Adjacency matrix A = |V| x |V| matrix ofBooleans or integers If there is an edge from avertex v to a vertex v’, then theelement A[v,v’] is 1, otherwise0. Incidence matrix IM = |V| x |E| matrix of integers IM[v,e] = 1 (incident), 0 (notincident) For directed graphs, may be -1(out) and +1 (in)
  5. 5. ExampleA.A. 2012/2013Tecniche di programmazione5AdjacencymatrixAdjacencylist
  6. 6. Adjacency list (undirected graph)A.A. 2012/2013Tecniche di programmazione651423123452 51 5 3 42 45 2 31 2 4
  7. 7. Adjacency list (undirected graph)A.A. 2012/2013Tecniche di programmazione751423123452 51 5 3 42 45 2 31 2 4Undirected ==>All edges arerepresented twice
  8. 8. Adjacency list (un-connected graph)A.A. 2012/2013Tecniche di programmazione8Un-connected graph,same rules
  9. 9. Adjacency list (directed graph)A.A. 2012/2013Tecniche di programmazione9514231234523 4351 2
  10. 10. Adjacency listA.A. 2012/2013Tecniche di programmazione10
  11. 11. Adjacency matrix (undirected graph)A.A. 2012/2013Tecniche di programmazione111 2 3 4 51 0 1 0 0 12 1 0 1 1 13 0 1 0 1 04 0 1 1 0 15 1 1 0 1 051423Undirected =>symmetric matrixNo self-loops: zerodiagonal
  12. 12. Adjacency matrix (undirected graph)A.A. 2012/2013Tecniche di programmazione121 2 3 4 51 1 0 0 12 1 1 13 1 04 1551423Undirected =>symmetric matrix50% of memory canbe saved
  13. 13. Adjacency matrix (directed graph)A.A. 2012/2013Tecniche di programmazione131 2 3 4 51 0 1 0 0 02 0 0 1 1 03 0 0 1 0 00 0 0 0 11 1 0 0 05142345From-vertex(out-edges)To-vertex(in-edges)Self-loops in thediagonal
  14. 14. Adjacency matrix (weighted graph)A.A. 2012/2013Tecniche di programmazione141 2 3 4 51 0 2 0 0 02 0 0 3 5 03 0 0 1 0 00 0 0 0 21 3 0 0 05142345Values = edge weight2312513
  15. 15. Adjacency matrixA.A. 2012/2013Tecniche di programmazione15
  16. 16. Incidence matrix (undirected graph)A.A. 2012/2013Tecniche di programmazione161 2 3 4 51 1 1 0 0 02 1 0 1 1 03 0 0 0 0 04 0 0 0 1 15 0 1 1 0 1v5v1v4v2v3Edges e1…e7e1e2 e3 e4e5e6e7601100700110Verticesv1…v5Exactly 2 “ones”in every column# of “ones” in arow = vertexdegree
  17. 17. Incidence matrix (directed graph)A.A. 2012/2013Tecniche di programmazione17v5v1v4v2v3e1e2 e3 e4e5e6e71 2 3 4 51 -1 +1 0 0 02 +1 0 +1 -1 03 0 0 0 0 04 0 0 0 +1 -15 0 -1 -1 0 +1Edges e1…e760-1+100700-1+10Verticesv1…v5Self loops can’tbe represented-1: exit+1: enterindegree =count(+1)outdegree =count(-1)
  18. 18. Complexity & trade-offsA.A. 2012/2013Tecniche di programmazione18Adjacency List Adjacency Matrix Incidence MatrixSpace O( |V| + |E| ) O( |V| x |V| ) O( |V| x |E| )Space For sparse graphs|E| << |V|2For dense graphs|E| ~ |V|2Check edge O(1+deg(v)) O(1) O(|E|) if v,v’ areknown, orO(1) if e is knownFind all adjacent O(1+deg(v)) O(|V|) O(|V|+|E|)
  19. 19. The JGraphT libraryRepresenting and visiting graphs
  20. 20. JGraphTA.A. 2012/2013Tecniche di programmazione20 (do not confuse Free Java graph librarythat provides graphobjects and algorithms Easy, type-safe andextensible thanks to<generics> Just add jgrapht-jdk1.6.jar to yourproject
  21. 21. JGraphT structureA.A. 2012/2013Tecniche di programmazione21Packagesorg.jgraphtThe front-end APIs interfaces and classes,including Graph, DirectedGraph and Algorithms provided with Utilities used by JGraphT Demo programs that help to get started with classes and listener interfaces, used to provide a changenotification mechanism on graph modification Extensions and integration means to other Generators for graphs of various Implementations of various Graph traversal data structures, algorithms, and utilitiesused by JGraphT.
  22. 22. Graph objectsA.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. 23. JGraphT main interfacesA.A. 2012/2013Tecniche di programmazione23
  24. 24. Graph classesA.A. 2012/2013Tecniche di programmazione24GraphDirectedGraph UndirectedGraph WeightedGraphIII IDefaultDirectedGraphorg.jgraphtorg.jgrapht.graphsDefaultDirectedWeightedGraphDirectedWeightedMultigraphDirectedWeightedPseudographDirectedMultigraph DirectedPseudographMultigraphPseudographSimpleDirectedGraphSimpleGraphSimpleWeightedGraphSimpleDirectedWeightedGraphWeightedMultigraph WeightedPseudograph
  25. 25. Graph classesA.A. 2012/2013Tecniche di programmazione25
  26. 26. Graph classesA.A. 2012/2013Tecniche di programmazione26Undirected Directed
  27. 27. Graph classesA.A. 2012/2013Tecniche di programmazione27WeightedNotweightedNotweighted
  28. 28. Graph classesA.A. 2012/2013Tecniche di programmazione28SimpleMultiPseudoNon simple (loops allowed, no multi edges)
  29. 29. Creating graphsA.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. 30. ExampleA.A. 2012/2013Tecniche di programmazione30r s t uv w x yz
  31. 31. For testing…A.A. 2012/2013Tecniche di programmazione31
  32. 32. ExampleA.A. 2012/2013Tecniche di programmazione32
  33. 33. ExampleA.A. 2012/2013Tecniche di programmazione33
  34. 34. Querying graph structureA.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. 35. Utility functionsA.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. 36. Graph visitsRepresenting and visiting graphs
  37. 37. Visit AlgorithmsA.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. 38. Breadth-First VisitA.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. 39. ExampleA.A. 2012/2013Tecniche di programmazione39r s t uv w x ySource = sL = 0S0 = {s}
  40. 40. ExampleA.A. 2012/2013Tecniche di programmazione40r s t uv w x yL = 1S0 = {s}S1 = {r, w}
  41. 41. ExampleA.A. 2012/2013Tecniche di programmazione41r s t uv w x yL = 2S1 = {r, w}S2 = {v, t, x}
  42. 42. ExampleA.A. 2012/2013Tecniche di programmazione42r s t uv w x yL = 3S2 = {v, t, x}S3 = {u, y}
  43. 43. BFS TreeA.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. 44. BFS TreeA.A. 2012/2013Tecniche di programmazione44r s t uv w x y
  45. 45. Minimum (shortest) pathsA.A. 2012/2013Tecniche di programmazione45 Shortest path: the minumum number of edges on anypath between two vertices The BFS procedure computes all minimum paths for allvertices, starting from the source vertex NB: unweighted graph : path length = number of edges
  46. 46. Depth First VisitA.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 tothe last visited one If no such vertex exist, go back one step to the previouslyvisited vertex Lends itself to recursive implementation Similar to tree visit procedures
  47. 47. DFS AlgorithmA.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. 48. ExampleA.A. 2012/2013Tecniche di programmazione48r s t uv w x ySource = s
  49. 49. ExampleA.A. 2012/2013Tecniche di programmazione49r s t uv w x ySource = sVisit r
  50. 50. ExampleA.A. 2012/2013Tecniche di programmazione50r s t uv w x ySource = sVisit rVisit v
  51. 51. ExampleA.A. 2012/2013Tecniche di programmazione51r s t uv w x ySource = sBack to rBack to sVisit w
  52. 52. ExampleA.A. 2012/2013Tecniche di programmazione52r s t uv w x ySource = sVisit wVisit t
  53. 53. ExampleA.A. 2012/2013Tecniche di programmazione53r s t uv w x ySource = sVisit wVisit tVisit u
  54. 54. ExampleA.A. 2012/2013Tecniche di programmazione54r s t uv w x ySource = sVisit wVisit tVisit uVisit y
  55. 55. ExampleA.A. 2012/2013Tecniche di programmazione55r s t uv w x ySource = sVisit wVisit tVisit uVisit yVisit x
  56. 56. ExampleA.A. 2012/2013Tecniche di programmazione56r s t uv w x ySource = sBack to yBack to uBack to tBack to wDFS treeBack to s = STOP
  57. 57. Edge classificationA.A. 2012/2013Tecniche di programmazione57 In an directed graph, after a DFS visit, all edges fall in oneof these 4 categories: T: Tree edges (belonging to the DFS tree) B: Back edges (not in T, and connect a vertex to one of itsancestors) F: Forward edges (not in T and B, and connect a vertex to oneof its descendants) C: Cross edges (all remaining edges)
  58. 58. ExampleA.A. 2012/2013Tecniche di programmazione58xyw vz sutDirected graph
  59. 59. ExampleA.A. 2012/2013Tecniche di programmazione59xyw vz sutDFS visit(sources: s, t)
  60. 60. ExampleA.A. 2012/2013Tecniche di programmazione60xyw vz sutEdge classificationT TT TTT B BBFC C C
  61. 61. CyclesA.A. 2012/2013Tecniche di programmazione61 Theorem: A directed graph is acyclic if and only if a depth-first visitdoes not produce any B edge
  62. 62. ComplexityA.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. 63. Visits in JGraphTRepresenting and visiting graphs
  64. 64. JGraphT and visitsA.A. 2012/2013Tecniche di programmazione64 Visits are called “traversals” Implemented through iterator classes Package org.jgrapht.traverse
  65. 65. Graph traversal classesA.A. 2012/2013Tecniche di programmazione65
  66. 66. Graph iteratorsA.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. 67. Types of traversal iteratorsA.A. 2012/2013Tecniche di programmazione67 BreadthFirstIterator DepthFirstIterator ClosestFirstIterator The metric for closest here is the path length from a startvertex. Graph.getEdgeWeight(Edge) is summed to calculatepath length. Optionally, path length may be bounded by a finiteradius. TopologicalOrderIterator A topological sort is a permutation p of the vertices ofa graph such that an edge {i,j} implies that i appearsbefore j in p. Only directed acyclic graphs can be topologicallysorted.
  68. 68. ResourcesA.A. 2012/2013Tecniche di programmazione68 Open Data Structures (in Java), Pat Morin, Algorithms Course Materials, Jeff Erickson, Graphbook - A book on algorithmic graph theory, DavidJoyner, MinhVan Nguyen, and David Phillips,
  69. 69. Licenza d’usoA.A. 2012/2013Tecniche di programmazione69 Queste diapositive sono distribuite con licenza Creative Commons“Attribuzione - Non commerciale - Condividi allo stesso modo (CCBY-NC-SA)” Sei libero: di riprodurre, distribuire, comunicare al pubblico, esporre in pubblico,rappresentare, eseguire e recitare questopera di modificare questopera Alle seguenti condizioni: Attribuzione — Devi attribuire la paternità dellopera agli autori originalie in modo tale da non suggerire che essi avallino te o il modo in cui tuusi lopera. Non commerciale — Non puoi usare questopera per fini commerciali. Condividi allo stesso modo — Se alteri o trasformi questopera, o se lausi per crearne unaltra, puoi distribuire lopera risultante solo con unalicenza identica o equivalente a questa.