data structures( 数据结构 ) course 12:graphs

44
Data Structures( Data Structures( 数数数数 数数数数 ) ) Course 12:Graphs Course 12:Graphs

Upload: zahir-ellis

Post on 02-Jan-2016

173 views

Category:

Documents


6 download

DESCRIPTION

Data Structures( 数据结构 ) Course 12:Graphs. Vocabulary. Graph 图 Vertex 顶点 Edge 边 Arc 弧 Directed Graph 有向图 Undirected Graph 无向图 Adjacent Vertices 邻接点 Path 路径 Cycle 圈 Strongly connected 强连通 Weekly connected 弱连通 Disjoint 未连通 depth-first traversal 深度优先遍历 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Data Structures( 数据结构 ) Course 12:Graphs

Data Structures(Data Structures( 数据结数据结构构 ))

Course 12:GraphsCourse 12:Graphs

Page 2: Data Structures( 数据结构 ) Course 12:Graphs

2西南财经大学天府学院

VocabularyVocabularyGraph 图Vertex 顶点Edge 边Arc 弧Directed Graph 有向图Undirected Graph 无向图Adjacent Vertices 邻接点Path 路径Cycle 圈Strongly connected 强连通Weekly connected 弱连通Disjoint 未连通depth-first traversal 深度优先遍历Breadth-first traversal 广度优先遍历

Adjacency matrix 邻接矩阵Adjacency list 邻接表Minimum Spanning tree 最小派生树

Page 3: Data Structures( 数据结构 ) Course 12:Graphs

3西南财经大学天府学院

Introduction to GraphsIntroduction to Graphs

Linear ListTreeGraph

Recall that a list is a collection of components in which 1. each component (except one, the first)

has exactly 1 predecessor. 2. each component (except one, the last)

has exactly 1 successor. multiple successorsUnique predecessor

Figure 7-1 A tree

Each node may have multiple successors as well as multiple predecessors

Page 4: Data Structures( 数据结构 ) Course 12:Graphs

4西南财经大学天府学院

Definition of graphDefinition of graph

A Graph is a collection of nodes, called verticesvertices, and a

collection of line segments, called edges edges (or arc arc), that

connecting pairs of vertices.

In other words, a graph consists of two sets, a set of

verticesvertices and a set of lineslines.

Page 5: Data Structures( 数据结构 ) Course 12:Graphs

5西南财经大学天府学院

TerminologyTerminology

Graph may be either directeddirected or undirectedundirected:

Directed graph(Digraph)

Each line has a directiondirection (arrow head)to its successor.

The lines in a directed graph are known as arcsarcs

G = (V, E),V:aggregate of Vertices , E:aggregate of edges 。 <vi, vj> ≠ <vj, vi>。

5

Page 6: Data Structures( 数据结构 ) Course 12:Graphs

6西南财经大学天府学院

TerminologyTerminology

Graph may be either directeddirected or undirectedundirected:

Undirected graph

Each line has nono directiondirection.

The lines in a undirected graph are known as edgesedges

G = (V,E), V:aggreaget of Vertices , E:aggreage of edges .<vi, vj> = <vj, vi>。

Page 7: Data Structures( 数据结构 ) Course 12:Graphs

7西南财经大学天府学院

TerminologyTerminology

PathPath:

A path is a sequence of verticesa sequence of vertices in which each vertex

is adjacent to the next one.

In the following figure, {A, B, C, E} is one path and {A,

B, E, F} is another.

Both directed and undirected graphs have paths.

Page 8: Data Structures( 数据结构 ) Course 12:Graphs

8西南财经大学天府学院

TerminologyTerminology

CycleCycle

A cycle is a pathpath consisting of at least three vertices that

starts and ends with the starts and ends with the same vertexsame vertex.

In the following subfigure (b), B, C, D, E, B is a cycle.

In a digraph, a path can only follow the directionfollow the direction of the

arcs

In an undirected graph, a path can move in either move in either

directiondirection along the edge

Cycle?

Page 9: Data Structures( 数据结构 ) Course 12:Graphs

9西南财经大学天府学院

TerminologyTerminology

LoopLoop

A loop is a special case of a cycle in which a single arca single arc

beings and ends with the same vertexbeings and ends with the same vertex.

Connected Connected

Two vertices are said to be connected if there is a path

between them.

A graph is said to be connected if there is a path from A graph is said to be connected if there is a path from

any vertex to any other vertex.any vertex to any other vertex.ConnectedConnected UnconnectedUnconnected

Page 10: Data Structures( 数据结构 ) Course 12:Graphs

10西南财经大学天府学院

TerminologyTerminology

Connected Connected (directed graph)

Strongly connected Strongly connected

A directed graph is strongly connected if there is there is a patha path

from each vertex to every other vertexfrom each vertex to every other vertex in the digraph.

Weakly connectedWeakly connected

A directed graph is weakly connected if at least two at least two

vertices are vertices are not connectednot connected.

DisjointDisjoint

A graph is disjoint if it is not connected.

Page 11: Data Structures( 数据结构 ) Course 12:Graphs

11西南财经大学天府学院

TerminologyTerminology

DegreeDegree

The degreedegree of a vertex is the number of lines incident to

it.

The degrees of the nodes A, C, D, F = 1

The degrees of the nodes B, E = 3

Page 12: Data Structures( 数据结构 ) Course 12:Graphs

12西南财经大学天府学院

TerminologyTerminology

The degreedegree of a vertex is the sum of the indegree and of the indegree and

outdegreeoutdegree of lines incident to it.

The outdegreeoutdegree of a vertex in a digraph is the the

number of arcs number of arcs leavingleaving the vertex the vertex.

The indegree indegree is the number of arcs the number of arcs enteringentering the the

vertexvertex.

12

Page 13: Data Structures( 数据结构 ) Course 12:Graphs

13西南财经大学天府学院

OperationsOperations

Add VertexAdd Vertex

Page 14: Data Structures( 数据结构 ) Course 12:Graphs

14西南财经大学天府学院

OperationsOperations

Delete VertexDelete Vertex

Add edgeAdd edge

Page 15: Data Structures( 数据结构 ) Course 12:Graphs

15西南财经大学天府学院

OperationsOperations

Delete edgeDelete edge

Find vertexFind vertex

Page 16: Data Structures( 数据结构 ) Course 12:Graphs

16西南财经大学天府学院

Traverse GraphTraverse Graph

Traverse graphTraverse grapheach vertex of the graphs be processed once and only onceeach vertex of the graphs be processed once and only once

we must ensure that we process the data in each vertex only once. There are multiple paths to a vertex, we use a visited flag at each vertex to solve this problem.

Depth-first TraversalDepth-first Traversal

Breadth-first TraversalBreadth-first Traversal

Page 17: Data Structures( 数据结构 ) Course 12:Graphs

17西南财经大学天府学院

Depth-first TraversalDepth-first Traversal

We process all of a vertex’s descendents before we move to

an adjacent vertex.

Depth-first traversal of a tree

Page 18: Data Structures( 数据结构 ) Course 12:Graphs

18西南财经大学天府学院

Depth-first TraversalDepth-first Traversal

depth-first traversal of a graph

processing the first vertex

Select any vertex adjacent to the first vertex and process it

Select an adjacent vertex until we reach a vertex with no

adjacent entries, back out of the structure.(stack)

The order in which the adjacent vertices are processed

depends on how the graph is physically stored.

In the depth –first traversal all of a node’s

descendents are processed before moving to an

adjacent

Page 19: Data Structures( 数据结构 ) Course 12:Graphs

19西南财经大学天府学院

Depth-first TraversalDepth-first Traversal

Page 20: Data Structures( 数据结构 ) Course 12:Graphs

20西南财经大学天府学院

Depth-first TraversalDepth-first Traversal

We Begin by pushing the first vertex A into the stackWe then loop, pop the stack, and , after processing the vertex. Push all of the adjacent vertices into the stack. Such as process Vertex X at step 2, we pop x from the stack process it, and then push the adjacent vertices G and H into the stack.When the stack is empty, the traversal is completes.

Page 21: Data Structures( 数据结构 ) Course 12:Graphs

21西南财经大学天府学院

Breadth-first TraversalBreadth-first Traversal

We processing all adjacent vertices of a vertex before going to the next level

Breadth-first traversal of a tree

Page 22: Data Structures( 数据结构 ) Course 12:Graphs

22西南财经大学天府学院

Breadth-first TraversalBreadth-first Traversal

Breadth-first traversal of a graph

processing the first vertex

Processing all of the first adjacent vertices

Pick the first adjacent vertex and processing all of its

adjacent vertices, then the second adjacent vertex and

so forth until we finished.(Queue)

In the Breadth –first traversal all adjacent vertices

are processed before processing the descendents

of a vertex.

Page 23: Data Structures( 数据结构 ) Course 12:Graphs

23西南财经大学天府学院

Breadth-first TraversalBreadth-first Traversal

Page 24: Data Structures( 数据结构 ) Course 12:Graphs

24西南财经大学天府学院

Breadth-first TraversalBreadth-first Traversal

We begin by enqueuing vertex A in the queueWe the loop, dequeuing the queue and processing the vertex from the front of the queue. After processing the vertex, we place all of its adjacent vertices into the queue.When the queue is empty, the traversal is complete

Page 25: Data Structures( 数据结构 ) Course 12:Graphs

25西南财经大学天府学院

Graph Storage StructureGraph Storage Structure

Represent a graph we need to store two setsThe vertices of the graphThe edges or arcs of the graph

Two most common structures Arrays Linked list

Page 26: Data Structures( 数据结构 ) Course 12:Graphs

26西南财经大学天府学院

Adjacency MatrixAdjacency Matrix

One-dimensional array to store the verticesTwo-dimensional array to store the edges or arcs

Page 27: Data Structures( 数据结构 ) Course 12:Graphs

27西南财经大学天府学院

Adjacency MatrixAdjacency Matrix

Page 28: Data Structures( 数据结构 ) Course 12:Graphs

28西南财经大学天府学院

Adjacency ListAdjacency List

Two-dimensional linked list to store the edges or arcs

Page 29: Data Structures( 数据结构 ) Course 12:Graphs

29西南财经大学天府学院

Graph AlgorithmsGraph Algorithms

Graph data Structure

Page 30: Data Structures( 数据结构 ) Course 12:Graphs

30西南财经大学天府学院

Graph AlgorithmsGraph Algorithms

Create GraphInsert VertexDelete VertexInsert ArcDelete ArcRetrieve VertexFirst ArcTraverse

Page 31: Data Structures( 数据结构 ) Course 12:Graphs

31西南财经大学天府学院

Depth-first Traversal AlgorithmDepth-first Traversal AlgorithmAlgorithm depthfirst (val graph<metadata>Processing the keys of the graph is depth-first

order.Pre graph is a pointer to a graph head structurePost vertices “processed”1 If (empty graph)

1 ReturnSet processed flags to not processed 2 walkPtr=graph.first3 Loop (walkPtr) 1 walkPtr->processed = 0 2 walkPtr =walkPtr->nextVertex4 End loop Process each vertex in list5 createStack(stack)6 walkPtr=graph.first7 loop(walkPtr not null) 1 if (walkPtr->Processed <2)

1 if (walkPtr->processed <1) Push and set flag to stack 1 puchStack(stack,walker)

2 walkPtr->processed =1

2 end if Process vertex at stack top 3 loop (not emptyStack(stack))

1 popStack(stack,vertexPtr)2 process(vertex->dataPtr)3 vertexPtr->processed =2

Push all Vertices from adjacency list 4 arcwalkPtr=vertexPr->arc 5 loop( arcwalkPtr not null) 1 vertToPtr=arcwalkPtr->destination

2 if (vertToPtr->processed is 0) 1 puchStack(sack,VertToPtr) 2 vertToPtr->Processed =1 3 end if 4 arcwalkPtr=arcwalkPtr->nextArc

6 end loop 4 end loop 2 end if 3 walkPtr-walkPtr->nextVertex 8 end loop 9 destroyStack(stack)10 ReturnEnd depthfirst

Page 32: Data Structures( 数据结构 ) Course 12:Graphs

32西南财经大学天府学院

Breadth-first Traversal AlgorithmBreadth-first Traversal AlgorithmAlgorithm Breadthfirst (val graph<metadata>

Processing the keys of the graph is Breadth-first order.

Pre graph is a pointer to a graph head structure

Post vertices “processed1 If (empty graph)

1 return

2 End if

Fist se all processed flags to not processed Falg:0– not processed, 1– enqueued, 2–

processed

3 createqueue(queue)

4 walkPtr=graph.first

5 Loop (walkPtr not null)

1 walkPtr->processed =0

2 walkPtr=walkPtr->nextVertex6 End loop

Process each vertex in vertex list

7 walkPtr =graph.first

8 Loop (walkPtr not null)1 if (walkPtr->Processed <2)

1 if (walkPtr->Processed <1)

Enqueue and set processed flag to 1 1 enqueue(queue,walkPtr) 2 walkPtr->Processed =1 2 end if

How process descendents of vertex at queue first 3 loop (not emptyQueue(queue))

1 dequeue(queue,vertexPtr)Process Vertex and flag as

processed2 process(vertexPtr)3 vertxPtr->processed =2Enqueue all vertices from

adjacency list 4 arcPtr=vertexPtr->arc5 loop (arcPtr not null) 1 toPtr =arcPtr->destination 2 if (toPtr -> processed =1) 1 enqueue(queue,toPtr) 2 toPtr->processed =1 3 end if 4 arcPtr=arcPtr->nextArc6 end loop

4 end loop 2 end if 3 walkPtr=walPtr->nextVertex

9 end loop 10 destroyQueue(queue)11 returnEnd breadthfirst

Page 33: Data Structures( 数据结构 ) Course 12:Graphs

33西南财经大学天府学院

NetworksNetworks

A network is a graph whose lines are weighted. It is also known as a weighted graph.

City airline Network

Page 34: Data Structures( 数据结构 ) Course 12:Graphs

34西南财经大学天府学院

Minimum Spanning TreeMinimum Spanning Tree

A spanning tree is a tree that contains all of the vertices in the graphA minimum spanning tree of a network such that the sum of its weights are guaranteed to be minimal.if there are duplicate weights, then these may be one or more minimum spanning tree.

Page 35: Data Structures( 数据结构 ) Course 12:Graphs

35西南财经大学天府学院

Minimum Spanning TreeMinimum Spanning Tree

City airline Network

Page 36: Data Structures( 数据结构 ) Course 12:Graphs

36西南财经大学天府学院

Minimum Spanning TreeMinimum Spanning Tree

Page 37: Data Structures( 数据结构 ) Course 12:Graphs

37西南财经大学天府学院

Minimum Spanning TreeMinimum Spanning Tree

From all the vertices in the tree. Select the edge with minimal value to a vertex not currently in the tree and insert it into the tree.

Page 38: Data Structures( 数据结构 ) Course 12:Graphs

38西南财经大学天府学院

Shortest pathShortest path

We find the shortest path between to vertices in networkThe Dijkstra algorithm is used to find the shortest path between any two nodes in a graph

Example : we need to find the shortest path from vertex A to any other vertex in the graph.

Page 39: Data Structures( 数据结构 ) Course 12:Graphs

39西南财经大学天府学院

Shortest pathShortest path

Page 40: Data Structures( 数据结构 ) Course 12:Graphs

40西南财经大学天府学院

Shortest pathShortest path

Page 41: Data Structures( 数据结构 ) Course 12:Graphs

41西南财经大学天府学院

Shortest pathShortest path

Insert the first vertex into the treeFrom every vertex already in the tree , examine the total path length to all adjacent vertices not in the tree. Select the edge with the minimum total path weight and insert it into the treeRepeat step 2 until all vertices are in the tree

Page 42: Data Structures( 数据结构 ) Course 12:Graphs

42西南财经大学天府学院

SummarySummary

A graph is a collection of nodes, called vertices, and a collection of line segments connection pairs of nodes, called edges or arcs.Graphs may be directed or undirected. A directed graph, or digraph is a graph is which each line has s direction. An undirected graph is a graph in which there is no direction on the lines. A line in a directed graph is called an arc.In a graph, two vertices are said to be adjacent if an edge directly connects themA path is a sequence of vertices in which each vertex is adjacent to the next one A cycle is a path of at least three vertices that starts and ends with the same vertexA loop is a special case of a cycle is which a single arc begins with the same vertex

Page 43: Data Structures( 数据结构 ) Course 12:Graphs

43西南财经大学天府学院

SummarySummary

A graph is said to be connected if ,for any two vertices, there is a path from one to the other. A graph is disjointed if it is not connected.The degree of a vertex is the number of the vertices adjacent to it. The outdegree of a vertex is the number of arcs leaving the node; the indegree of a vertex is the number of arcs entering the node.Six operations have been defined for a graph:add a vertex, delete a vertex, add an edge, delete an edge, find a node, and traverse the graph.There are two standard graph traversals: depth-first and breadth first.

In the depth-first traversal, all of the node’s descendents are processed before moving to an adjacent nodeIn the breadth-first traversal, all of the adjacent vertices are processed before processing the descendents of a vertex

Page 44: Data Structures( 数据结构 ) Course 12:Graphs

44西南财经大学天府学院

SummarySummary

To represent a graph in a computer, we need to store two sets of information: the first sets represents the vertices and the second sets represents the edges.The most common methods used to store a graph are the adjacency matrix method and the adjacency list methodsA network is a graph whose lines are weighted.A spanning tree is a graph whose lines are weightedA minimum spanning tree is a spanning tree in which the total weight of the edges is the minimum.Another common algorithm in a graph is to find the shotest pathe between two vertices.