- By
**nike** - Follow User

- 132 Views
- Uploaded on

Download Presentation
## PowerPoint Slideshow about 'Chapter 27 Graph Applications' - nike

**An Image/Link below is provided (as is) to download presentation**

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Objectives (1)

- To give applications of 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)

Objectives (2)

- 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)

Modeling Using Graphs

- The problem of finding the shortest distance between two cities can be modeled using a graph where one measures the distance between two vertices (cities)

Seven Bridges of Königsberg (1)

- The city of Königsberg, Prussia was divided by the Pregel river
- There were two islands on the river
- The city and island were connected by seven bridges
- Problem
- How can one take a walk, cross each bridge exactly once, and return to the starting point?

Seven Bridges of Königsberg (2)

Each land mass was represented by a dot (vertex or node) and each bridge was represented by a line (edge)

Seven Bridges of Königsberg (3)

- Is there a path from any vertex, traversing all the edges exactly once and returning to the starting vertex?
- No
- Euler proved that for such a path to exist, each vertex must have an even number of edges

A vertex represents an airport and stores the three-letter airport code

An edge represents a flight route between two airports and stores the mileage of the route

Graph Example849

PVD

1843

ORD

142

SFO

802

LGA

1743

337

1387

HNL

2555

1099

1233

LAX

1120

DFW

MIA

saddleback.edu

att.net

cox.net

Delores

Sam

Jane

Other Applications- Electronic circuits
- Printed circuit board
- Integrated circuit
- Transportation networks
- Highway network
- Flight network
- Computer networks
- Local area network
- Internet
- Web
- Databases
- Entity-relationship diagram

cslab1C

cslab1D

math.saddleback.edu

qwest.net

Basic Graph Terminology

- Graph Theory – the study of graphs
- Graph– A mathematical structure that represents relationships among entities in the real world
- It consists of a non-empty set of vertices, nodes or points and a set of edges that connect the vertices
- It is defined as G = (V,E) where V represents the set of vertices and E represents the set of edge
- For example V = {“Seattle”, “San Francisco”, “Los Angeles”, …) and E = {{ “Seattle”,” San Francisco”}, {{ “Seattle”,” Chicago”}, {{ “Seattle”,” Denver”}, …}

Directed edge

ordered pair of vertices (u,v)

first vertex u is the origin

second vertex v is the destination

e.g., a flight

Directed graph

all the edges are directed

e.g., route network

Edge Types (1)flight

AA 1206

ORD

PVD

ORD

PVD

ATL

Undirected edge

unordered pair of vertices (u,v)

Move both direction between vertices

e.g., a flight route

Undirected graph

all the edges are undirected

e.g., flight network

Edge Types (2)849

miles

ORD

PVD

ORD

PVD

ATL

Weighted Graphs

- In a weightedgraph, each edge has an associated numerical value, called the weight of the edge
- Edge weights may represent distances, costs, etc.
- Example:
- In a flight route graph, the weight of an edge represents the distance in miles between the endpoint airports

849

PVD

1843

ORD

142

SFO

802

LGA

1205

1743

337

1387

HNL

2555

1099

1233

LAX

1120

DFW

MIA

Adjacent Vertices and Edges

- Vertices U and V areadjacent if there is an edge whose end vertices are U and V
- Edges a and b areadjacent if they are connected to the same vertex
- Two vertices are called neighborsif they are adjacent
- Two edges are called neighbors if they are adjacent

V

a

b

U

d

X

c

e

W

g

f

Y

Incident Edges, Degree, and Loops

- An edge that joins two vertices is said to be incident to both vertices
- a is incident to both U and V
- Degreeof a vertex V, deg(V)
- Number of incident edges of V
- X has degree 5
- Loop
- Edge that connects a vertex to itself
- j is a loop

V

a

b

h

j

Z

U

d

X

c

e

i

W

g

f

Y

Parallel Edges and Simple Graphs

- Collection
- Group of edges
- Parallel edges
- Two undirected edges that have the same end vertices
- Two directed edges that have the same origin and destination
- h and i are parallel edges
- A graph is simple if it does not have parallel edges or loops

V

h

a

b

Z

U

d

X

j

c

e

i

W

g

f

Y

Subgraphs

- A subgraph S of a graph G is a graph such that
- The vertices of S are a subset of the vertices of G
- The edges of S are a subset of the edges of G
- A spanning subgraphof G is a subgraph that contains all the vertices of G

Subgraph

Spanning subgraph

Representing Graphs

- Representing Vertices
- Representing Edges
- Edge Array
- Edge Objects
- Adjacency Matrices
- Adjacency Lists

Representing Vertices

- Vertices can be stored in an array
- For example
- String [ ] vertices = {“Seattle”, “Denver”, “Boston”}
- vertices [0] = Seattle;
- vertices [1] = Denver;
- vertices [2] = Boston;
- Vertices can be referenced by its name or index
- Vertices can be objects of any type

Representing Edges: Edge Array

- Edges can be stored in a two dimensional array
- For example
- int [ ] edges ={ {0,1}, {0,3}, {0,5}}
- where i and j are the indices of the vertices

Representing Edges: Edge Objects (1)

- Another way to represent edges is to define edges as objects and then store the edges in an array using java.util.ArrayList

public class Edge {

int u;

int v;

public Edge (int u, int v) {

this.u=u;

this.v = v;

}

}

Representing Edges: Edge Objects (2)

- One can then store all the edges using the following:

java.util.ArrayList<Edge> list = new java.util.ArrayList<Edge> ();

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

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

list.add(new Edge (0,5));

…

Representing edges in an array is intuitive but not efficient

Representing Edges: Adjacency Matrices (1)

- Another way to represent edges
- Assume that a graph has n vertices, one can use a two-dimensional n x n array (adjacencyMatrix) to represent the edges where each element in the array is either a0or a1
- adjacencyMatrix[i][j] is1if there is a an edge from vertex ito vertex j other it is 0

Representing Edges: Adjacency Matrices (2)

- If the graph is undirected, the matrix will be symmetrical because adjacencyMatrix[i][j] is the same as adjacencyMatrix[j][i]
- See adjacency matrix in section 27.3.5
- int [ ] adjacencyMatrix ={ {0,1,0,1,0,1,0,0,0,0,0,0}, // Seattle
- Since there are edges between Seattle and San Francisco, Denver, and Chicago

Representing Edges: Adjacency Lists (1)

- Another way to represent edges
- To represent edges using an Adjacency list, one defines an array of linked lists (section 27.3.5)
- The array has n entries where each entry represents a vertex
- The linked list for vertex i contains all the vertices j such that there is an edge from vertex ito vertex j

Representing Edges: Adjacency Lists (2)

- To represent the edges in Figure 27.1 one uses

java.util.LinkedList [ ] neighbors = new java.util.LinkedList(12);

- list[0] contains all the vertices adjacent to vertex 0 (Seattle)
- See Figure 27.5

Adjacency Matrices vs. Adjacency Lists

- If the graph is dense (lots of edges), adjacency matrix are more efficient
- If the graph is sparse (few edges), adjacency lists are more efficient
- It takes O(1) time to check whether two vertices are connected using a adjacency matrix
- It takes O(n) time to print all the edges using a adjacency list where n is the number of edges

Modeling Graphs

- One can define an interface called Graphthat contains all the common operations for graphs
- Lets define an abstract class called AbstractGraphthat partially implements the Graph interface
- Concrete class will be added to the design
- Unweighted Graph
- Weighted Graph

Similar framework as the Java Collections framework

Common Graph Operations

- Obtain the number of vertices
- Obtain all the vertices
- Obtain the vertex object with a specified index
- Obtain the index of a vertex with a specified name
- Obtain the neighbors of a vertex
- Obtain the adjacency matrix
- Obtain the degree of a vertex
- Perform a depth-first search
- Perform a breadth-first search

AbstractGraph Class Data Fields

- The AbstractGraphclass defines the following data fields
- vertices
- Used to store the vertices
- neighbors
- Used to store the edges in the adjacency lists
- neighbors[i] stores all the vertices adjacent to vertex i

AbstractGraph Class Methods

- Four overloaded constructors are used to create graphs from arrays or lists of edges and vertices
- The createAdjacencyLists ( )method creates adjacency lists from edges in an array or list depending on its parameters
- The getAdjacencyMatrix ( ) method returns a two-dimensional array representing an adjacency matrix of edges

Source Code for the Graph Related Classes

Graph

AbstractGraph

UnweightedGraph

TestGraph

Listings 27.2 – 27.4

Graph Traversals

- Systematic procedure for exploring a graph by examining all of its vertices and edges
- Process of visiting each vertex in the graph exactly once

Graph Traversals Methods

- Two common methods
- Depth-first traversal (depth-first search)
- Breadth-first traversal (breadth-first search)
- Both traversals result in a spanning tree
- A spanning tree of a graph is a subgraph that is a tree and connects all the vertices in the graph

AbstractGraph.Tree

- Tree is an inner class defined within the AbstractGraphclass (see page 872)
- AbstractGraph.Treeisdifferent from the Treeinterface which was defined in a section 27.5.2
- AbstractGraph.Treedescribes a search order of the nodes in a graph

AbstractGraph.Tree

Tree is inner class of AbstractGraph

AbstractGraph.Tree Class Methods (1)

- TheTreeclass methods
- Getroot () method – returns the root of a tree
- getSearchOrders () method – obtains the order of the vertices
- getParent (v)method – finds the parent of vertex v
- getNumberOfVerticesFound () method – returns the number of vertices searched

AbstractGraph.Tree Class Methods (2)

- printPath (v) method – displays a path from the root to v
- printTree () method – displays all the edges in the tree
- pathIterator (int v) method – returns an iterator for a path from the root to the vertex v
- The iterator is an instance of the PathIteratorclass which implements java.util.Iterator
- The PathIteratorclass must implement the hasNext(), next(), and remove() methods

Cycle

Circular sequence of alternating vertices and edges

Each edge is preceded and followed by vertices

Simple cycle

Cycle such that all its vertices and edges are distinct

Examples

C1=(V,b,X,g,Y,f,W,c,U,a) is a simple cycle

C2=(U,c,W,e,X,g,Y,f,W,d,V,a) is a cycle that is not simple

Directed cycle

All edges are directed

Traversed along their direction

CyclesV

a

b

d

U

X

Z

h

c

e

C1

W

g

f

C2

Y

Depth-First Search

- Depth-first search (DFS) is a general technique for traversing a graph
- A DFS traversal of a graph G
- Visits all the vertices G
- Determines whether G is connected

Depth-First Search

- The DFS of a graph is like the depth-first search of a tree discussed in section 27.2.4
- In the case of a tree, the search starts from the root
- In a graph, the search can start from any vertex
- The DFS of a graph first visits a vertex then recursively visits all the vertices adjacent to that vertex
- Graph may contains cycles that lead to an infinite recursion
- One needs to keep track of the vertices that have been visited

Depth-First Search Algorithm (1)

- The search starts from some vertex v
- After visiting v, the next vertex to be visited is the first unvisited neighbor of v
- If v has no unvisited neighbor, backtrack to the vertex from which we reached v

Depth-First Search Algorithm (2)

dfs(vertex v) {

visit v;

for each neighbor w of v

if (w has not been visited) {

dfs(w);

}

}

- One uses an array called isVisitedto denote whether a vertex has been visited

Depth-First Search Example

- First visit 0, then visit its neighbor 1

Depth-First Search Example

- 1 has three neighbors (0, 2, and 4)
- 0 has already been visited, so lets visit 2

Depth-First Search Example

- 2 has three neighbors (0, 1, and 3)
- 0and1 have already been visited, so lets visit 3
- Order is 0, 1, 2, 3

Depth-First Search Example

- Since all the neighbors of 3 have been visited, backtrack to 2and then 1
- 0and2 have already been visited, so lets visit 4
- Backtrack to 1and then to 0
- The search is search ends

Another Depth-First Search Example

- Search order (assuming that the left edges are chosen before right edges)
- A, B, D, F, E, C, G

Depth-First Search Order

DFS Order (1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

DFS Example

- Start with (A,E)
- A, E, I, M, N, K, O, P, L, H, D, C, B, F
- Backtrack to C and then visit G and J

A

B

C

D

A

B

C

D

E

F

G

H

E

F

G

H

L

I

J

K

I

J

K

L

M

N

O

P

M

N

O

P

Depth-First Implementation

- Uses recursion
- The dfs(int v) method returns an instance of the Tree class with vertex v as the root
- This method stores the vertices searched in a list called searchOrders
- This method stores the parent of each vertex in array called parent
- Uses theisVisitedarray to indicate whether a vertex has been visited
- It invokes the helper method dfs(v,searchOrders, isVisited) to perform the depth-first search

Applications of the DFS (1)

- Detecting whether a graph is connected
- A graph is connected if there is a path between any two vertices in the graph (See Exercise 27.1)
- Detecting whether there is a path between two vertices (See Exercise 27.2)
- Finding a path between two vertices (See Exercise 27.3)

Applications of the DFS (2)

- 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.4)
- Detecting whether there is a cycle in the graph (See Exercise 27.5)

DFS Time Complexity

- The time complexity of the DFS algorithm is O(|E| + |V| ) where |E| is the number of edges and |V|is the number of vertices since each edge and vertex is visited only once

Breadth-First Search

- Breadth-first search (BFS) is a general technique for traversing a graph
- A BFS traversal of a graph G
- Visits all the vertices and edges of G
- Proceeds in rounds and subdivides the vertices into levels

Breadth-First Search (BFS)

- BFS traversal of a graph is like the breadth-first traversal of a tree discussed in §27.2.4
- With BFS 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
- The BFS traversal visits a vertex, then all its adjacent vertices, then all the vertices adjacent to those vertices, and so on

BFS Algorithm

- Starts at the root, s
- Level 0
- Round 1
- Visits and marks the vertices adjacent to s
- Level 1 nodes
- Round 2
- Visits and marks all the vertices adjacent to the level 1 nodes
- Level 2 nodes
- Continue this process until all the vertices have been visited
- BFS visits a node, then its neighbors, and then its neighbors’ neighbors, and so on

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

visit u;

for each neighbor w of u

if w has not been visited {

add w into the queue;

mark w visited;

}

}

}

Listing 27.7

Breadth-First Search Example (1)

- First visit 0, then visit all its neighbors 1, 2 ,3

Breadth-First Search Example (2)

- Vertex 1has three neighbors 0, 2 ,4
- Since 0and2have been visited, visit 4
- Vertex 2 has three neighbors 0, 1, and 3which have been visited
- Vertex 4has two neighbors 1and 3which have been visited
- The search is complete

Breadth-First Order

BFS Order (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

Breadth-First Implementation

- The bfs(int v) method returns an instance of the Tree class with vertex v as the root
- This method stores the vertices searched in a list called searchOrders
- This method stores the parent of each vertex in array called parent
- Uses thea linked list for a queue
- Uses theisVisitedarray to indicate whether a vertex has been visited
- The search starts with vertex v
- V is added to the queue and is marked visited
- The method examines each vertex in the queue and adds it to searchOrders
- The method adds each unvisited neighbor to the queue

Applications of the BFS (1)

- 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
- One 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

BFS Time Complexity

- The time complexity of the BFS algorithm is O(|E| + |V| ) where |E|is the number of edges and |V| is the number of vertices since each edge and vertex is visited only once

Applications of the BFS (2)

- 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.6)

The Nine Tail Problem Description

- 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

The Nine Tail Problem Implementation

- Each state represents a node on a graph
- If 0 represents heads and 1 represents tails then there are 512 (29) states
- Targeted state (node) is all 1’s(see Figure 27.17)
- The problem is to find the shortest path for the input state (node) to the targeted state (node)

The Hamiltonian Path Problem

- AHamiltonian 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

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

Find a Knight’s Tour

- To 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

KnightTourModel

KnightTourApp

KnightTourApp

Download Presentation

Connecting to Server..