0% found this document useful (0 votes)
14 views35 pages

Graphs

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
14 views35 pages

Graphs

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

Graphs and Applications

Chapter 28

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
Objectives
➢ To model real-world problems using graphs and explain the Seven Bridges of
Königsberg problem.
➢ To describe the graph terminologies: vertices, edges, simple graphs,
weighted/unweighted graphs, and directed/undirected graphs
➢ To represent vertices and edges using lists, edge arrays, edge objects,
adjacency matrices, and adjacency lists
➢ To model graphs using the Graph interface, the AbstractGraph class, and the
UnweightedGraph class.
➢ To represent the traversal of a graph using the AbstractGraph.Tree class .
➢ To design and implement depth-first search.
➢ To design and implement breadth-first search.
➢ To solve the nine-tail problem using breadth-first search .

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
2
Seven Bridges of Königsberg
A

C
D
Island 1
Island 2

C D

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
3
Modeling Using Graphs
Seattle (0)

Boston (6)

Chicago (5)

New York (7)

Denver (3)

San Francisco (1) Kansas City (4)

Los Angeles (2) Atlanta (8)

Dallas (10)

Houston (11)

Miami (9)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
4
Basic Graph Terminologies
➢ What is a graph?
– A graph is a mathematical structure that represents relationships among entities in
the real world.
– For convenience, we define a graph as G=(V, E) where V represents a set of
vertices and E represents a set of edges.
Seattle (0) V = {"Seattle", "San Francisco", "Los
Boston (6)
Angeles","Denver", "Kansas City", "Chicago",
Chicago (5) "Boston", "New York","Atlanta", "Miami",
New York (7) "Dallas", "Houston"};
Denver (3)

E = {{"Seattle", "San Francisco"},{"Seattle",


San Francisco (1) Kansas City (4) "Chicago"},{"Seattle", "Denver"}, {"San
Francisco", "Denver"},
Los Angeles (2) Atlanta (8)
...
Dallas (10)

};
Houston (11)

Miami (9)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
Basic Graph Terminologies
➢Directed vs. undirected graphs

➢Weighted vs. unweighted graphs


– Edges may be weighted or unweighted. For example, you can
assign a weight for each edge in the flight network to indicate the
flight time between the two cities.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
Basic Graph Terminologies
➢Adjacent vertices
– Two vertices in a graph are said to be adjacent if they
are connected by the same edge.
➢Incident
– An edge in a graph that joins two vertices is said to be
incident to both vertices.
➢Degree
– The degree of a vertex is the number of edges incident
to it
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
7
Basic Graph Terminologies
➢ Neighbour
– Two vertices are called neighbours if they are adjacent.
Similarly, two edges are called neighbours if they are
adjacent.
➢ Loop
– A loop is an edge that links a vertex to itself.
➢ Parallel edge
– If two vertices are connected by two or more edges, these
edges are called parallel edges

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
8
Basic Graph Terminologies
➢ Simple graph
– A simple graph is one that doesn’t have any
loops or parallel edges
➢ Complete graph A D

– In a complete graph, every two pairs of B E


vertices are connected
➢ Spanning tree C

– A spanning tree of a graph G is a connected A D

subgraph of G and the subgraph is a tree that


contains all vertices in G. B E

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
9
Representing Graphs
➢ To implement graphs, we need a representation of Vertices and
edges.
1. Representing Vertices
– We can use an array list or an array to represent vertices
2. Representing Edges
– There are 4 main ways for representing edges:
Edge Array
Edge Objects
Adjacency Matrices
Adjacency Lists

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
Representing Vertices
1. Representing vertices using arrays
String[] vertices = {“Seattle“, “San Francisco“, “Los Angles”,
“Denver”, “Kansas City”, “Chicago”, … };
OR
City[] vertices = {city0, city1, … };
public class City {
…..
}
2. Using a Array Lists
List<String> vertices = new ArrayList<>();
OR
List <City> verteces = new ArrayList<>();

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
11
Representing Edges: Edge Array

➢ int[][] edges = {{0, 1}, {0, 3} {0, 5}, {1, 0}, {1,
2}, … };
➢ The size of the inner array is always 2.
➢ The size of the outer array is the number of the
edges in the graph

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
12
Representing Edges: Edge Object
public class Edge {
int u, v;
public Edge(int u, int v) {
this.u = u;
this.v = v;
}

List<Edge> list = new ArrayList<>();


list.add(new Edge(0, 1)); list.add(new Edge(0, 3)); …

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
13
Representing Edges: Adjacency
Matrix
int[][] adjacencyMatrix = {
{0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0}, // Seattle
{1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, // San Francisco
{0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0}, // Los Angeles
{1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0}, // Denver
{0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0}, // Kansas City
{1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0}, // Chicago
{0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0}, // Boston
{0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0}, // New York
{0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1}, // Atlanta
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1}, // Miami
{0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1}, // Dallas
{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0} // Houston
};
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
14
Representing Edges: Adjacency List
List<Integer>[] neighbors = new LinkedList<Integer>[12];

Seattle neighbors[0] 1 3 5
San Francisco neighbors[1] 0 2 3
Los Angeles neighbors[2] 1 3 4 10
Denver neighbors[3] 0 1 2 4 5
Kansas City neighbors[4] 2 3 5 7 8 10
Chicago neighbors[5] 0 3 4 7 11
Boston neighbors[6] 5 7
New York neighbors[7] 4 5 6 8
Atlanta neighbors[8] 4 7 9 10 11
Miami neighbors[9] 8 11
Dallas neighbors[10]
2 4 8 11
Houston neighbors[11]
10 8 9

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
15
Example: Vertex Represenation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
16
Modeling Graphs

UnweightedGraph

Graph AbstractGraph
WeightedGraph

Interface Abstract Class Concrete Classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
17
The Graph Interface
«interface» The generic type V is the type for vertices.
Graph<V>
+getSize(): int Returns the number of vertices in the graph.
+getVertices(): List<V> Returns the vertices in the graph.
+getVertex(index: int): V Returns the vertex object for the specified vertex index.
+getIndex(v: V): int Returns the index for the specified vertex.
+getNeighbors(index: int): List<Integer> Returns the neighbors of vertex with the specified index.
+getDegree(index: int): int Returns the degree for a specified vertex index.
+getAdjacencyMatrix(): int[][] Returns the adjacency matrix.
+printAdjacencyMatrix(): void Prints the adjacency matrix.
+printEdges(): void Prints the edges.
+dfs(index: int): AbstractGraph<V>.Tree Obtains a depth-first search tree.
+bfs(index: int): AbstractGraph<V>.Tree Obtains a breadth-first search tree.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
18
«interface» The generic type V is the type for vertices.
Graph<V>
+getSize(): int Returns the number of vertices in the graph.
+getVertices(): List<V> Returns the vertices in the graph.
+getVertex(index: int): V Returns the vertex object for the specified vertex index.
+getIndex(v: V): int Returns the index for the specified vertex.
+getNeighbors(index: int): List<Integer> Returns the neighbors of vertex with the specified index.
+getDegree(index: int): int
+printEdges(): void
Returns the degree for a specified vertex index.
Prints the edges. Graph
+clear(): void Clears the graph.
+addVertex(v: V): void Adds a vertex to the graph.
+addEdge(u: int, v: int): void Adds an edge to the graph.
+dfs(v: int): AbstractGraph<V>.Tree Obtains a depth-first search tree starting from v.

AbstractGraph
+bfs(v: int): AbstractGraph<V>.Tree Obtains a breadth-first search tree starting from v.
.

AbstractGraph<V>
#vertices: List<V> Vertices in the graph.
#neighbors: List<List<Integer>> Neighbors for each vertex in the graph.

#AbstractGraph() Constructs an empty graph.


#AbstractGraph(edges: int[][], vertices: Constructs a graph with the specified edges and vertices
V[]) stored in arrays.
UnweightedGraph
#AbstractGraph(edges: List<Edge>, Constructs a graph with the specified edges and vertices
vertices: List<V>) stored in lists.
#AbstractGraph(edges: int[][], Constructs a graph with the specified edges in an array
numberOfVertices: int)
and the integer vertices 1, 2, ....
#AbstractGraph(edges: List<Edge>,
numberOfVertices: int)
Inner classes Tree is defined here
Constructs a graph with the specified edges in a list and
the integer vertices 1, 2, …. TestGraph
UnweightedGraph<V>
+UnweightedGraph() Constructs an empty unweighted graph.
+UnweightedGraph(edges: int[][], Constructs a graph with the specified edges and vertices
vertices: V[]) in arrays.
+UnweightedGraph(edges: List<Edge>, Constructs a graph with the specified edges and vertices
vertices: List<V>) stored in lists.
+UnweightedGraph(edges: List<Edge>, Constructs a graph with the specified edges in an array
numberOfVertices: int) and the integer vertices 1, 2, ....
+UnweightedGraph(edges: int[][], Constructs a graph with the specified edges in a list and
numberOfVertices: int) the integer vertices 1, 2, ….
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
19
Graph Traversals
➢ There are two approaches to Graph traversal
– Depth-first search
– breadth-first search
➢ Both traversals result in a spanning tree, which can be
modeled using a class.
AbstractGraph.Tree

-root: int The root of the tree.


-parent: int[] The parents of the vertices.
-searchOrders: java.util.List<Integer> The orders for traversing the vertices.
+Tree(root: int, parent: int[], Constructs a tree with the specified root, parent, and
searchOrders: List<Integer>) searchOrders.
+Tree(root: int, parent: int[]) Constructs a tree with the specified root and parent with
no specified searchOrders.
+getRoot(): int Returns the root of the tree.
+getSearchOrders(): List Returns the order of vertices searched.
+getParent(v: int): int Returns the parent of vertex v.
+getNumberOfVerticesFound(): int Returns the number of vertices searched.
+pathIterator(v: int): java.util.Iterator Returns an iterator for the path from the root to vertex v.
+printPath(v: int): void Displays a path from the root to the specified vertex.
+printTree(): void Displays tree with the root and all edges.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
20
Depth-First Search
➢ The depth-first search of a graph is like the depth-first search of a
tree.
➢ In the case of a tree, the search starts from the root. In a graph, the
search can start from any vertex.

dfs(vertex v)
{
visit v;
for each neighbor w of v
if (w has not been visited) {
dfs(w);
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
21
Depth-First Search Example

0 1 0 1 0 1

2 2 2

3 4 3 4 3 4

0 1 0 1

2 2

3 4 3 4

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
22
Depth-First Search Example

TestDFS
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
23
Breadth-First Search
➢ The breadth-first traversal of a graph is like the
breadth-first traversal of a tree.
➢ With breadth-first traversal of a tree, the nodes are
visited level by level.
➢ First the root is visited, then all the children of the root,
then the grandchildren of the root from left to right, and
so on.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
Breadth-First Search Example

0 1 0 1 0 1

2 2 2

3 4 3 4 3 4

Queue: 0 isVisited[0] = true


Queue: 1 2 3 isVisited[1] = true, isVisited[2] = true,
isVisited[3] = true
Queue: 2 3 4
isVisited[4] = true

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
25
Breadth-First Search Algorithm
bfs(vertex v) {
create an empty queue for storing vertices to be visited;
add v into the queue;
mark v visited;
while the queue is not empty {
dequeue a vertex, say u, from the queue
process u;
for each neighbor w of u
if w has not been visited {
add w into the queue;
mark w visited;
}
}
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
26
Breadth-First Search Example
Seattle

2097 Boston
983
Chicago
1331 214
807
1003 New York
787
Denver
533
1267 1260
599
888
San Francisco 1015 Kansas City

381 1663
864

496
Los Angeles 1435 Atlanta
781
810
Dallas
661
239

Houston 1187

Miami

TestBFS
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
27
Applications of the DFS
➢ Detecting whether a graph is connected.
– Search the graph starting from any vertex. If the number of vertices searched is
the same as the number of vertices in the graph, the graph is connected.
Otherwise, the graph is not connected.
➢ Detecting whether there is a path between two vertices.
➢ Finding a path between two vertices.
➢ Finding all connected components. A connected component is a maximal
connected subgraph in which every pair of vertices are connected by a
path.
➢ Detecting whether there is a cycle in the graph.
➢ Finding a cycle in the graph.
➢ Testing whether a graph is bipartite. A graph is bipartite if the
vertices of the graph can be divided into two disjoint sets such that
no edges exist between vertices in the same set.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
28
Applications of the BFS
➢ Detecting whether a graph is connected.
– A graph is connected if there is a path between any two vertices in the graph.

➢ Detecting whether there is a path between two vertices.

➢ Finding a shortest path between two vertices.


– You can prove that the path between the root and any node in the BFS tree is the shortest path
between the root and the node

➢ Finding all connected components. A connected component is a maximal connected


subgraph in which every pair of vertices are connected by a path.

➢ Detecting whether there is a cycle in the graph.

➢ Finding a cycle in the graph.

➢ Testing whether a graph is bipartite. A graph is bipartite if the vertices of the graph can
be divided into two disjoint sets such that no edges exist between vertices in the same
set.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
29
«interface» The generic type V is the type for vertices.
Graph<V>
+getSize(): int Returns the number of vertices in the graph.
+getVertices(): List<V> Returns the vertices in the graph.
+getVertex(index: int): V Returns the vertex object for the specified vertex index.
+getIndex(v: V): int Returns the index for the specified vertex.
+getNeighbors(index: int): List<Integer> Returns the neighbors of vertex with the specified index.
+getDegree(index: int): int
+printEdges(): void
Returns the degree for a specified vertex index.
Prints the edges. Graph
+clear(): void Clears the graph.
+addVertex(v: V): void Adds a vertex to the graph.
+addEdge(u: int, v: int): void Adds an edge to the graph.
+dfs(v: int): AbstractGraph<V>.Tree Obtains a depth-first search tree starting from v.

AbstractGraph
+bfs(v: int): AbstractGraph<V>.Tree Obtains a breadth-first search tree starting from v.
.

AbstractGraph<V>
#vertices: List<V> Vertices in the graph.
#neighbors: List<List<Integer>> Neighbors for each vertex in the graph.

#AbstractGraph() Constructs an empty graph.


#AbstractGraph(edges: int[][], vertices: Constructs a graph with the specified edges and vertices
V[]) stored in arrays.
UnweightedGraph
#AbstractGraph(edges: List<Edge>, Constructs a graph with the specified edges and vertices
vertices: List<V>) stored in lists.
#AbstractGraph(edges: int[][], Constructs a graph with the specified edges in an array
numberOfVertices: int)
and the integer vertices 1, 2, ....
#AbstractGraph(edges: List<Edge>,
numberOfVertices: int)
Inner classes Tree is defined here
Constructs a graph with the specified edges in a list and
the integer vertices 1, 2, …. TestGraph
UnweightedGraph<V>
+UnweightedGraph() Constructs an empty unweighted graph.
+UnweightedGraph(edges: int[][], Constructs a graph with the specified edges and vertices
vertices: V[]) in arrays.
+UnweightedGraph(edges: List<Edge>, Constructs a graph with the specified edges and vertices
vertices: List<V>) stored in lists.
+UnweightedGraph(edges: List<Edge>, Constructs a graph with the specified edges in an array
numberOfVertices: int) and the integer vertices 1, 2, ....
+UnweightedGraph(edges: int[][], Constructs a graph with the specified edges in a list and
numberOfVertices: int) the integer vertices 1, 2, ….
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
30
DFS: The Connected Circles Problem

ConnectedCircles
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
31
BFS: The Nine Tail Problem
➢ The problem is stated as follows.
– Nine coins are placed in a three by three matrix with some face up and some
face down.
– A legal move is to take any coin that is face up and reverse it, together with
the coins adjacent to it (this does not include coins that are diagonally
adjacent).
– Your task is to find the minimum number of the moves that lead to all coins
face down.

H H H H H H T T T
T T T T H T T T T
H H H T T T T T T

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
Model the Nine Tail Problem
0 1 2 3 511
0 0 0 0 0 0 0 0 0 0 0 0 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 ….. 1 1 1
0 0 0 0 0 1 0 1 0 0 1 1 1 1 1

408 488 240 30 47 51


1 1 0 1 1 1 0 1 1 0 0 0 0 0 0 0 0 0
0 1 1 1 0 1 1 1 0 0 1 1 1 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 0 1 1

0 0 0
1 1 1
0 0 0
56

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
33
NineTailModel
NineTailModel
#tree: AbstractGraph<Integer>.Tree A tree rooted at node 511.
+NineTailModel() Constructs a model for the nine tail problem and obtains the
tree.
+getShortestPath(nodeIndex: int): Returns a path from the specified node to the root. The path
List<Integer> returned consists of the node labels in a list.
#getEdges(): Returns a list of Edge objects for the graph.
List<AbstractGraph.Edge>
+getNode(index: int): char[] Returns a node consisting of nine characters of H’s and T’s.
+getIndex(node: char[]): int Returns the index of the specified node.
+getFlippedNode(node: char[], Flips the node at the specified position and returns the index
position: int): int of the flipped node.
+flipACell(node: char[], row: int, Flips the node at the specified row and column.
column: int): void
+printNode(node: char[]): void Displays the node to the console.

NineTailModel NineTail
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
34
Companion
Website
The Nine Tail Problem

If you entered HHHTTTTTT, see what happens. There is an


error in this program. Fix it as an exercise. Also as an
exercise, color the cells that are flipped.

NineTailModel NineTailApp
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
35

You might also like