Docsity

Graphs and Sets - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Graphs and Sets - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Chapter 9

Graphs and Sets

Lecture 19

What is a graph?

  • A data structure that consists of a set of

nodes ( vertices ) and a set of edges between the vertices.

  • The set of edges describes relationships

among the vertices.

1 2

3 4

Definitions

  • Graph: A data structure that consists of a set

of nodes and a set of edges that relate the nodes to each other

  • Vertex: A node in a graph
  • Edge (arc): A pair of vertices representing a

connection between two nodes in a graph

  • Undirected graph: A graph in which the edges

have no direction

  • Directed graph (digraph): A graph in which

each edge is directed from one vertex to another (or the same) vertex

Formally

  • a graph G is defined as follows:

G = (V,E)

where

  • V(G) is a finite, nonempty set of vertices
  • E(G) is a set of edges
    • written as pairs of vertices

A directed graph

A graph in which each edge is directed from one vertex to another (or the same) vertex

The order of vertices in E

is important for

directed graphs!!

A directed graph

Trees are special cases of graphs!

  • Path: A sequence of vertices that

connects two nodes in a graph

  • The length of a path is the number of

edges in the path.

e.g., a path from 1 to 4

1 2

3 4

<1, 2, 3, 4>

Graph terminology

Graph terminology

Complete graph: A graph in which every vertex

is directly connected to every other vertex

  • What is the number of edges E in a

complete directed graph with V vertices?

E=V * (V-1)

Graph terminology (cont.)

or O(V^2 )

A weighted graph

Weighted graph: A graph in which each edge carries a value

to node x?

from node x?

Adjacency Matrix for Flight Connections

Array-Based Implementation (cont.)

  • Memory required
    • O(V+V^2 )=O(V^2 )
  • Preferred when
    • The graph is dense: E = O(V^2 )
  • Advantage
    • Can quickly determine if there is an edge between two vertices
  • Disadvantage
    • Consumes significant memory for sparse large graphs

Adjacency List Representation of Graphs

to node x?

from node x?

Link-List-based Implementation (cont.)

  • Memory required
    • O(V + E)
  • Preferred when
    • for sparse graphs: E = O(V)
  • Disadvantage
    • No quick way to determine the vertices adjacent to a given vertex
  • Advantage
    • Can quickly determine the vertices adjacent from a given vertex

O(V) for sparse graphs since E=O(V) O(V^2 ) for dense graphs since E=O(V 2 )