31
1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pear son Education, Inc. All rights reserved. 0132130807 Chapter 27 Graphs and Applications

Chapter 27 Graphs and Applications

  • Upload
    casta

  • View
    57

  • Download
    1

Embed Size (px)

DESCRIPTION

Chapter 27 Graphs and Applications. Objectives. To model real-world problems using graphs and explain the Seven Bridges of Königsberg problem (§27.1). To describe the graph terminologies: vertices, edges, simple graphs, weighted/unweighted graphs, and directed/undirected graphs (§27.2). - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 27 Graphs and Applications

1Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Chapter 27 Graphs and Applications

Page 2: Chapter 27 Graphs and Applications

2Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Objectives To model real-world problems using graphs and explain the Seven

Bridges of Königsberg problem (§27.1). To describe the graph terminologies: vertices, edges, simple graphs,

weighted/unweighted graphs, and directed/undirected graphs (§27.2). To represent vertices and edges using lists, adjacent matrices, and

adjacent lists (§27.3). To model graphs using the Graph interface, the AbstractGraph class,

and the UnweightedGraph class (§27.4). To represent the traversal of a graph using the AbstractGraph.Tree

class (§27.5). To design and implement depth-first search (§27.6). To design and implement breadth-first search (§27.7). To solve the nine-tail problem using breadth-first search (§27.8). To solve the Knight’s Tour problem by reducing it to a Hamiltonian

path problem (§27.9).

Page 3: Chapter 27 Graphs and Applications

3Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Modeling Using Graphs

Seattle

San Francisco

Los Angeles

Denver

Chicago

Kansas City

Houston

Boston

New York

Atlanta

Miami

Dallas

Page 4: Chapter 27 Graphs and Applications

4Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Weighted Graph Animationwww.cs.armstrong.edu/liang/animation/GraphLearningTool.html

Page 5: Chapter 27 Graphs and Applications

5Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Seven Bridges of Königsberg

Island 1 Island 2

B

A

C D

A

C

B

D

Page 6: Chapter 27 Graphs and Applications

6Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Basic Graph Terminologies What is a graph?

Define a graph

Directed vs. undirected graphs

Weighted vs. unweighted graphs

Adjacent vertices

Incident

Degree

Neighbor

loop

Page 7: Chapter 27 Graphs and Applications

7Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Basic Graph Terminologies Parallel edge

Simple graph

Complete graph

Spanning tree

Page 8: Chapter 27 Graphs and Applications

8Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Representing Graphs Representing Vertices

Representing Edges: Edge Array

Representing Edges: Edge Objects

Representing Edges: Adjacency Matrices

Representing Edges: Adjacency Lists

Page 9: Chapter 27 Graphs and Applications

9Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Representing Vertices String[] vertices = {“Seattle“, “San Francisco“, … };

City[] vertices = {city0, city1, … };

public class City {

}

List<String> vertices;

Page 10: Chapter 27 Graphs and Applications

10Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Representing Edges: Edge Array int[][] edges = {{0, 1}, {0, 3} {0, 5}, {1, 0}, {1, 2}, … };

Page 11: Chapter 27 Graphs and Applications

11Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

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<Edge>();

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

Page 12: Chapter 27 Graphs and Applications

12Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

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};

Page 13: Chapter 27 Graphs and Applications

13Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Representing Edges: Adjacency List

neighbors[0]

neighbors[1]

neighbors[2]

neighbors[3]

neighbors[4]

neighbors[5]

neighbors[6]

neighbors[7]

neighbors[8]

neighbors[9]

neighbors[10]

neighbors[11]

Seattle San Francisco

Los Angeles Denver Kansas City Chicago Boston

New York

Atlanta Miami Dallas

Houston

1 3 5

0 2 3

0 1 2 4 5

1 3 4 10

2 3 5 7 8 10 0 3 4 7 11

5 7

4 5 6 8

4 7 9 10 11 8 11

2 4 8 11

10 8 9

List<Integer>[] neighbors = new LinkedList<Integer>[12];

Page 14: Chapter 27 Graphs and Applications

14Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Modeling Graphs

Graph WeightedGraph

AbstractGraph

UnweightedGraph

Interface Abstract Class Concrete Classes

Page 15: Chapter 27 Graphs and Applications

15Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Graph

TestGraph

AbstractGraph

UnweightedGraph

TestGraph

«interface» Graph<V>

+getSize(): int +getVertices(): List<V> +getVertex(index: int): V +getIndex(v: V): int +getNeighbors(index: int): List<Integer> +getDegree(index: int): int +getAdjacencyMatrix(): int[][] +printAdjacencyMatrix(): void +printEdges(): void

+dfs(index: int): AbstractGraph<V>.Tree +bfs(index: int): AbstractGraph<V>.Tree

Returns the number of vertices in the graph. Returns the vertices in the graph. Returns the vertex object for the specified vertex index. Returns the index for the specified vertex. Returns the neighbors of vertex with the specified index. Returns the degree for a specified vertex index. Returns the adjacency matrix. Prints the adjacency matrix. Prints the edges. Obtains a depth-first search tree. Obtains a breadth-first search tree.

AbstractGraph<V> #vertices: List<V> #neighbors: List<List<Integer>>

#AbstractGraph(edges: int[][], vertices: V[]) #AbstractGraph(edges: List<Edge>,

vertices: List<V>) #AbstractGraph(edges: int[][],

numberOfVertices: int) #AbstractGraph(edges: List<Edge>,

numberOfVertices: int) Inner classes Tree is defined here

Vertices in the graph. Neighbors for each vertex in the graph.

Constructs a graph with the specified edges and vertices in arrays.

Constructs a graph with the specified edges and vertices stored in lists.

Constructs a graph with the specified edges in an array and the integer vertices 1, 2, ....

Constructs a graph with the specified edges in a list and the integer vertices 1, 2, ….

UnweightedGraph<V>

+UnweightedGraph(edges: int[][], vertices: V[])

+UnweightedGraph(edges: List<Edge>, vertices: List<V>)

+UnweightedGraph(edges: List<Edge>, numberOfVertices: int)

+UnweightedGraph(edges: int[][], numberOfVertices: int)

Constructs a graph with the specified edges and vertices in arrays.

Constructs a graph with the specified edges and vertices stored in lists.

Constructs a graph with the specified edges in an array and the integer vertices 1, 2, ....

Constructs a graph with the specified edges in a list and the integer vertices 1, 2, ….

The generic type V is the type for vertices.

Page 16: Chapter 27 Graphs and Applications

16Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Graph Visualization

GraphView Run

Displayable Interface DisplayUSMap

Page 17: Chapter 27 Graphs and Applications

17Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Graph Traversals Depth-first search and breadth-first search

Both traversals result in a spanning tree, which can be modeled using a class.

AbstractGraph.Tree -root: int -parent: int[] -searchOrders: java.util.List<Integer>

+Tree(root: int, parent: int[], searchOrders: List<Integer>)

+Tree(root: int, parent: int[])

+getRoot(): int +getSearchOrders(): List +getParent(v: int): int +getNumberOfVerticesFound(): int +pathIterator(v: int): java.util.Iterator +printPath(v: int): void +printTree(): void

The root of the tree. The parents of the vertices. The orders for traversing the vertices.

Constructs a tree with the specified root, parent, and searchOrders.

Constructs a tree with the specified root and parent with no specified searchOrders.

Returns the root of the tree. Returns the order of vertices searched. Returns the parent of vertex v. Returns the number of vertices searched. Returns an iterator for the path from the root to vertex v. Displays a path from the root to the specified vertex. Displays tree with the root and all edges.

Page 18: Chapter 27 Graphs and Applications

18Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Depth-First Search The depth-first search of a graph is like the depth-first search of a tree discussed in §25.2.3, “Tree Traversal.” 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); }}

Page 19: Chapter 27 Graphs and Applications

19Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Depth-First Search Example

0 1

2

3 4

0 1

2

3 4

0 1

2

3 4

0 1

2

3 4

0 1

2

3 4

Page 20: Chapter 27 Graphs and Applications

20Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Depth-First Search Example

Seattle

San Francisco

Los Angeles

Denver

Chicago

Kansas City

Houston

Boston

New York

Atlanta

Miami

661

888

1187

810 Dallas

1331

2097

1003 807

381

1015

1267

1663

1435

239

496

781

864

1260

983

787

214

533

599

TestDFSTestDFS

Page 21: Chapter 27 Graphs and Applications

21Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

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 (See Exercise 27.2.)

Detecting whether there is a path between two vertices. (See Exercise 27.3)

Finding a path between two vertices. (See Exercise 27.3)

Finding all connected components. A connected component is a maximal connected subgraph in which every pair of vertices are connected by a path. (See Exercise 27.2)

Detecting whether there is a cycle in the graph. (See Exercise 27.4)

Finding a cycle in the graph. (See Exercise 27.5)

Page 22: Chapter 27 Graphs and Applications

22Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Breadth-First Search The breadth-first traversal of a graph is like the breadth-first traversal of a tree discussed in §25.2.3, “Tree Traversal.” 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.

Page 23: Chapter 27 Graphs and Applications

23Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Breadth-First Search Algorithmbfs(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; } }}

Page 24: Chapter 27 Graphs and Applications

24Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Breadth-First Search Example

0 1

2

3 4

0 1

2

3 4

0 1

2

3 4

Queue: 0

Queue: 1 2 3

Queue: 2 3 4

isVisited[0] = true

isVisited[1] = true, isVisited[2] = true, isVisited[3] = true

isVisited[4] = true

Page 25: Chapter 27 Graphs and Applications

25Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Breadth-First Search Example

TestBFSTestBFS

Seattle

San Francisco

Los Angeles

Denver

Chicago

Kansas City

Houston

Boston

New York

Atlanta

Miami

661

888

1187

810 Dallas

1331

2097

1003 807

381

1015

1267

1663

1435

239

496

781

864

1260

983

787

214

533

599

Page 26: Chapter 27 Graphs and Applications

26Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

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 (see Review Question 27.10).

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. (See Exercise 27.4)Finding a cycle in the graph. (See Exercise 27.5)

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. (See Exercise 27.8)

Page 27: Chapter 27 Graphs and Applications

27Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

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 T

T

T

H

H

H

H

H

H T

H

T

H

H

T

T

T

T T

T

T

T

T

T

T

T

Page 28: Chapter 27 Graphs and Applications

28Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

The Nine Tail Problem

NineTailAppNineTailAppNineTailModel

Page 29: Chapter 27 Graphs and Applications

29Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

The Hamiltonian Path Problem A Hamiltonian path in a graph is a path that visits each vertex in the graph exactly once. A Hamiltonian cycle is a cycle that visits each vertex in the graph exactly once and returns to the starting vertex. A Hamiltonian path and cycle have many applications.

Page 30: Chapter 27 Graphs and Applications

30Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

The Knight’s Tour Problem The Knight’s Tour is a well-known classic problem. The objective is to move a knight, starting from any square on a chessboard, to every other square once. Note that the knight makes only L-shape moves (two spaces in one direction and one space in a perpendicular direction). As shown in Figure 27.19(a), the knight can move to eight squares.

0 1 2 3 4 5 6 7

0

1

2

3

4

5

6

7

Page 31: Chapter 27 Graphs and Applications

31Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Find a Knight’s TourTo solve the Knight’s Tour problem, create a graph with 64 vertices representing all the squares in the chessboard. Two vertices are connected if a knight can move between the two vertices.

KnightTourAppKnightTourAppKnightTourModel