1 of 33

Lecture 24:

Graphs & Iterators

CS 136: Spring 2024

Katie Keith

2 of 33

Record on Zoom

3 of 33

  • Please fill out the final project partner preference Google form.
    • Due: Monday (May 5) at 10pm ET.

  • Pre-registration info session today at 2:35pm

📣 Announcements

4 of 33

  • Graph ADT & Definitions
  • Adjacency Lists & Adjacency Matrices
  • Java’s Iterable and Iterator interfaces

🎯 Today’s Learning Objectives

5 of 33

📚Readings

  • Sedgewick and Wayne. Algorithms. Section 4.1.

6 of 33

Multiple data structures can implement the same ADT

Data Structures

List

Finite number of elements

(same element may occur more than once)

Stack

Last in first out (LIFO) operations

Symbol Table

Associates a key with a value

Graph

A set of vertices, pairs of which are connected by edges

Queue

First in first out (FIFO) operations

ADT

7 of 33

Graphs

A graph is a set of vertices and a collection of edges, each of which connect a pair of vertices.

Vertex

Edge

Undirected edge (no arrow on either side)

Preview: We’ll talk about directed & weighted graphs next week

8 of 33

Application: New York City Subway

Vertices = Subway stops; Edges = track between stop

Important graph operations:

  • Traversal between vertices
  • Finding shortest paths between vertices

9 of 33

Application: US Railways

Vertices = cities; Edges = rail lines connecting the cities

Equivalent

Note, the connections matter, not the exact location of each vertex

10 of 33

Guesses of this graph?

11 of 33

Application: The internet, circa 1998

12 of 33

Undirected Graph ADT

Look-ahead: We’ll define this

13 of 33

Degree

The degree of vertex v is the number of edges incident (attached) to v.

What’s the degree of a?

Of c?

14 of 33

Path

A path in a graph is a sequence of vertices connected by edges, with no repeated edges.

How many distinct paths are there between b and c?

15 of 33

Reachability and Connectedness

16 of 33

Reachability

A vertex v in graph G is reachable from vertex u in G if there is a path from u to v.

Is a reachable from b? Is c reachable from b?

17 of 33

Connectedness

An undirected graph G is connected if for every pair of vertices u, v in graph G, v is reachable from u.

This subgraph (vertices d, a, b) is connected

This subgraph (a single vertex c) is also connected

18 of 33

  • Graph ADT & Definitions
  • Adjacency Lists & Adjacency Matrices
  • Java’s Iterable and Iterator interfaces

🎯 Today’s Learning Objectives

19 of 33

ADTs to Data Structures

Adjacency matrices

ADTs

Data Structures

Adjacency lists

List

Finite number of elements

(same element may occur more than once)

Stack

Last in first out (LIFO) operations

Queue

First in first out (FIFO) operations

Symbol Table

Associates a key with a value

Graphs

A set of vertices, pairs of which are connected by edges

20 of 33

Adjacency List Representation

An adjacency list representation of an undirected graph consists of an array where indices are vertices and each array index contains a reference to a linked list of adjacent vertices.

Look-ahead: We’ll come back and implement.

21 of 33

Adjacency Matrix Representation

An adjacency matrix representation of an undirected graph consists of a 2-dimensional array of size VxV where V is the number of vertices in the graph.

A 1 indicates an edge exists (here between vertex 5 and 2)

A 0 indicates an edge does not exists (here between vertex 1 and 5)

Vertices

22 of 33

Adjacency matrix in Java

int V = 10; // num. vertices

boolean[][] adj = new boolean[V][V]; // adjacency matrix

adj[0][5] = true; // add edge between vertex 0 and 5

adj[5][0] = true;

2-D array type

Add edge for both 0->5 and 5->0 for undirected graph

23 of 33

Thinking about time-space tradeoff, brainstorm when is an adjacency list representation better? When is an adjacency matrix representation better?

Adjacency list

Adjacency matrix

💡Think-pair-share

24 of 33

Trade-offs: Adjacency lists versus matrices

Adjacency list

Adjacency matrix

Adding an edge (time)

O(1)

O(1)

Memory (space)

O(V+E)

O(V2 )

Checking if an edge exists from vertex v to u (time)

O(degree(v))

O(1)

Let V be the number of vertices in our graph and let E be the number of edges.

25 of 33

  • Graph ADT & Definitions
  • Adjacency Lists & Adjacency Matrices
  • Java’s Iterable and Iterator interfaces

🎯 Today’s Learning Objectives

26 of 33

Iterators

Goal: Be able to use an enhanced for loop for an object of our custom class/reference type (e.g., set of adjacent vertices).

for (int number : numbers) {

System.out.println(number);

}

Enhanced for-loop

27 of 33

Java’s Iterable and Iterator

Java defines two interfaces that facilitate enhanced for loops.

Why? Abstraction! With an iterator, we don't need to know how the collection is implemented (e.g., array, linked list, hash table etc.).

Checks if there are more elements to iterate over

Returns the next item in the iteration

28 of 33

Aside: CS History

  • Iterators were invented by Dr. Barbara Liskov in her CLU programming language 1974.
  • She was the first woman to be awarded a PhD in computer science (in 1968 from Stanford).
  • Dr. Liskov also invented abstract data types (ADTs)
  • She won the Turing Award (the considered the “Nobel Prize” of computer science) in 2008.

29 of 33

AdjacencyList.java

Bag.java

💻

30 of 33

Development Tip: Exceptions

import java.util.NoSuchElementException;

...

if (!hasNext()) throw new NoSuchElementException();

In Java, an Exception is an event that disrupts the normal flow of a program's execution, usually caused by errors like invalid input, missing files, or failed operations.

Many different exceptions you can import

New object

Keyword to trigger exception at runtime

31 of 33

  • Graph ADT & Definitions
  • Adjacency Lists & Adjacency Matrices
  • Java’s Iterable and Iterator interfaces

🎯 Today’s Learning Objectives

32 of 33

33 of 33