35
A D B E C V = {A,B,C,D,E} E = {(A,C),(A,D),(A,E) (B,E),(C,A),(C,B), (C,D),(D,C),(E,D) }

(B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 1'&

$%

Graphs

A graph consists of a set of vertices V and a set of edges

E = f(v1; v2)jv1; v2 2 V g.

If (v1; v2) are ordered, we have a directed graph.

A

D

B

EC

V = {A,B,C,D,E}E = {(A,C),(A,D),(A,E) (B,E),(C,A),(C,B), (C,D),(D,C),(E,D) }

Page 2: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 2'&

$%

If (v1; v2) are unordered, we have a undirected graph.

A

D

B

EC

V = {A,B,C,D,E}E = {(A,C),(A,D),(A,E) (B,C),(B,E),(C,A),(C,B), (C,D),(D,C),(D,A),(D,E), (E,A),(E,B),(E,D)}

Page 3: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 3'&

$%

Terminology

Vertices vi and vj are adjacent if either (vi; vj) 2 E or (vj ; vi) 2 E.

A path in a graph is a sequence of vertices v1; v2; : : : ; vn where all

(vi; vi+1) 2 E; 8i = 1; : : : ; n� 1. The length of this path is n� 1.

A

D

B

EC

V = {A,B,C,D,E}E = {(A,C),(A,D),(A,E) (B,E),(C,A),(C,B), (C,D),(D,C),(E,D) }

Some paths:

� A,D,C,B � A,C,A,E,D,C,A

� A,D,C,A

Page 4: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

4

'&

$%

MoreTerminology

�Simplepath{Allverticesaredistinctexceptpossiblythev1

andvn.

�Cycle{pathoflength>=1wherev1

=vn.

�Weightedgraph{agraphwith\costs"associatedwitheach

edge.

�ConnectedComponents{Adirectedgraphisstrongly

connectedifthereisadirectedpathfromeveryvertextoevery

othervertex.Adirectedgraphisweaklyconnectedifforevery

pairofverticesV1

andV2 ,thereiseitherapathP(V1 ,V2 )or

P(V2 ,V1 ).

Page 5: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 5'&

$%

Directed Acyclic Graph (DAG)

A directed graph containing no cycles

A

D

B

EC

V = {A,B,C,D,E}E = {(A,C),(A,D),(A,E) (B,E),(C,B),(C,D), (E,D)}

A tree is also an example of a directed acyclic graph.

Page 6: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

6

'&

$%

GraphADT

�Constructor:!

Graph

Action:createanewgraph

�InsertVertex:(Graph,vertex)!

Graph

Action:Addanewvertextothegraph.

Pre:vertexshouldnotalreadybeinthegraph.

�InsertEdge:(Graph,vertex1,vertex2)!

Graph

Action:Addanedgetothegraph.

Pre:vertex1

andvertex2

mustalreadybeinthegraph.

Page 7: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

7

'&

$%

�DeleteVertex:(Graph,vertex)!

Graph

Action:Removevertexfromthegraph.Alsoremoveany

edgesoftheform(vertex1 ,vertex2 ),whereeithervertex1

orvertex2

isvertex.

Pre:CalltoInsertVertex(vertex)shouldhaveoccurred

previously.

�DeleteEdge:(Graph,vertex1,vertex2 )!

Graph

Action:Removetheedge(vertex1,vertex2 )fromthegraph.

Pre:CalltoInsertEdge(vertex1 ,vertex2 )shouldhave

occurredpreviously.

�GetNeighbors:(Graph,vertex)!

vertexlist

Action:Findallvertex1

where(vertex,vertex1 )isanedge

inthegraph.

Pre:vertexmustbeinthegraph.

Page 8: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

8

'&

$%

TraversingaGraph:DFS

DepthFirstSearch(DFS)

main()f

for(visnodeingraph)

if(vhasnotbeenvisited)

dfs(v);

gdfs(vertexv)

markvashavingbeenvisited

list=neighborsofv

whilethereisanunvisitedneighborwofv

dfs(w)

Page 9: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 9'&

$%

D

FE

B

C

A A

C

B

D

E F

Cross arcs

DF tree arcs

Back arcs

Forward arcs

Page 10: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

10

'&

$%

dfs(A)

dfs(B)

dfs(C)

Balreadyvisited

dfs(D)

Calreadyvisited

dfs(E)

Calreadyvisited

dfs(F)

Calreadyvisited

Dalreadyvisited

Page 11: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

11

'&

$%

BreadthFirst

Queueq;

main()f

initializeallnodes{visited=false,queued=false

for(visnodeingraph)

if(vhasnotbeenvisited)bfs(v);

gbfs(vertexv)

q.enqueue(v)

whilenotq.empty()do

w=q.dequeue()

markwashavingbeenvisited

forallneighborsxwithqueued=false,

queued=trueforxq.enqueue(x)

Page 12: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 12'&

$%

D

FE

B

C

A A

C

B

D

E F

Cross arcs

DF tree arcs

Back arcs

Forward arcs

Page 13: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 1'&

$%

Representation of Graphs

A

D

B

EC

V = {A,B,C,D,E}E = {(A,C),(A,D),(A,E) (B,E),(C,A),(C,B), (C,D),(D,C),(E,D) }

� Adjacency matrix { Space O(jV j2)

A B C D E

A 0 0 1 1 1

B 0 0 0 0 1

C 1 0 0 1 0

D 0 1 1 0 0

E 0 0 0 1 0

Page 14: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 2'&

$%

� Adjacency list

2 3 4

4

0 3

1 2

3

A=0

B=1

C=2

D=3

E=4

Page 15: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

Adjacency table

template <int max_size>class Digraph { int count; // number of vertices, at most max_size bool adjacency[max_size][max_size];}

Page 16: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

Adjacency Liststypedef int Vertex;template <int max_size>class Digraph { int count; List <Vertex> neighbors[max_size];};

Page 17: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

Adjacency Lists cont’d

class Edge; // forward declarationclass Vertex { Edge *first_edge; // start of adjacency list Vertex *next_vertex; // next vertex on linked list of vertices}

class Edge { Vertex *end_point; // vertex to which the edge points Edge *next_edge; // next edge on adjacency list};class Digraph { Vertex *first_vertex; // header for list of vertices};

Page 18: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 8'&

$%

Topological sorting on DAGS

Suppose we have 10 tasks and a graph represents a partial order on

these tasks where Ti ! Tj means that task Ti must be complete

before task Tj can start.

2

3

4

1

5

6

7

8

9

10

What order should the tasks be done?

Some possibilities:

1 ! 2 ! 3 ! 4 ! 5 ! 6 ! 7 ! 8 ! 9 ! 10

1 ! 3 ! 4 ! 6 ! 2 ! 5 ! 7 ! 9 ! 8 ! 10

1 ! 4 ! 3 ! 2 ! 6 ! 5 ! 9 ! 8 ! 7 ! 10

Page 19: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

Topological sort

• Depth-first– find node with no successor and place it last in

order– use depth-first traversal

• Breadth-first– find node with no predecessor and place it first

in order– use breadth-first traversal

Page 20: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

typedef int Vertex;

template <int graph_size>

class Digraph {

public:

Digraph();

void read();

void write();

void depth_sort(List<Vertex> &topological_order);

void breadth_sort(List<Vertex> &topological_order);

private:

int count; List <Vertex> neighbors[graph_size];

void recursive_depth_sort(Vertex v, bool visited[],

List<Vertex> &topological_order);

};

Page 21: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

template <int graph_size>

void Digraph<graph_size>::depth_sort(List<Vertex> &topological_order)

/*Post: The vertices of the Digraph are placed into List topological_order

with a depth-first traversal of those vertices that do not belong to a cycle.

Uses: Methods of class List, and function recursive_depth_sort to perform

depth-first traversal.*/

{ bool visited[graph_size];

Vertex v;

for (v = 0; v < count; v++) visited[v] = false;

topological_order.clear();

for (v = 0; v < count; v++)

if (!visited[v]) // Add v and its successors into topological order.

recursive_depth_sort(v, visited, topological_order);

}

Page 22: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

template <int graph_size>

void Digraph<graph_size>::recursive_depth_sort(Vertex v, bool *visited,

List<Vertex> &topological_order)

{

visited[v] = true;

int degree = neighbors[v].size();

for (int i = 0; i < degree; i++) {

Vertex w; // A (neighboring) successor of v

neighbors[v].retrieve(i, w);

if (!visited[w]) // Order the successors of w.

recursive_depth_sort(w, visited, topological_order);

}

topological_order.insert(0, v); // Put v into topological_order.

}

Page 23: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS

310

9

'&

$%

TopologicalSort

1.8verticesv,computepredv ,thenumberoftasksthatvertex

dependson(directly).

2.Findavertexw

wherepredw

=0.Outputw.

3.8verticesxwherew

!

x,decrementpredx

4.repeatsteps2and3untileither:

(a)Nomoreverticesinthegraph|

SUCCESS

(b)Moretasksbutnonewithpredv

=0|

FAILURE{wedid

notstartwithaDAG

Page 24: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

template <int graph_size>

void Digraph<graph_size>::breadth_sort(List<Vertex> &topological_order)

{

topological_order.clear();

Vertex v, w;

int predecessor_count[graph_size];

for (v = 0; v < count; v++) predecessor_count[v] = 0;

for (v = 0; v < count; v++)

for (int i = 0; i < neighbors[v].size(); i++) {

// Loop over all edges v -- w.

neighbors[v].retrieve(i, w);

predecessor_count[w]++;

}

Page 25: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

Queue ready_to_process; for (v = 0; v < count; v++) if (predecessor_count[v] == 0) ready_to_process.append(v);while (!ready_to_process.empty( )) { ready_to_process.retrieve(v); topological_order.insert(topological_order.size(), v); for (int j = 0; j < neighbors[v].size(); j++) { // Traverse successors of v. neighbors[v].retrieve(j, w); predecessor_count[w]--; if (predecessor_count[w] == 0) ready_to_process.append(w); } ready_to_process.serve(); }}

Page 26: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

13

'&

$%

SpanningTrees

Ifthegraphisundirected,DFSandBFSaregoodwaystoseeif

thegraphisconnected(i.e.possiblepathbetweenallnodes).

Thesetraversalsde�nespanningtrees.

Page 27: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 14'&

$%

Spanning Trees

A B

EC D

D

A B

EC

D

A B

EC

D

A B

EC

Initial Graph

Spanning Trees

Page 28: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 15'&

$%

Weighted Graphs

A graph consists of a set of vertices V , a set of edges

E = f(v1; v2)jv1; v2 2 V g, and a weighting function: E ! I.

E

CB

A

D

F

15

2012

13

11

2428 A

B

C

D

E

F

C 28 D 24

C 14 E 20

A 28 B 15 E 12

A 24 F 11

B 20 C 12 F 13

D 11 E 13

Page 29: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS310

16

'&

$%

Minimum

SpanningTrees{Kruskal's

�Greedy

�Idea:considerthelightestedges�rst

Algorithm:

1.First,weneedtoviewthegraphofnnodesasnseparate

components.

2.Considertheedgesinincreasingorderoftheirweights.

3.Ifanedgehasendsin2di�erentcomponents,selectthatedge

forthespanningtreeandmergethecomponents.Otherwise,

theedgewillnotbepartoftheMST

Page 30: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 17'&

$%

FE

CB

A

D

2428

1211

13

1416

F

FE

C

1211

16 FE

C

1211

16

E

CB

A

D

2428

1211

13

1416

FE

C

1211

16

A

D

2428

A

D

2428

B13

14

B13

14

A

D

2428

B13

14

Page 31: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS

310

3

'&

$%

ShortestPaths{WeightedGraphs

�Dijkstra'sAlgorithm{Singlesource,alldestinations

�Assumesnonegativeedges

Page 32: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 4'&

$%

D

FE

B

C

A

94

4

62

58

3

5

7

Page 33: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS 310 5'&

$%

Graph G

Page 34: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS

310

6

'&

$%

Algorithm

1.Initialize:

settled=finitialg

8i,distance(i)=1,successor(i)=NULL

2.8nodesj:2settled,computedistance(j)=

min(distance(j),distance(i)+cost(i,j)wherei!

jandi2

settled).

3.Choosei!

kwherei2settled,k:2settled,andkhasthe

smallestofthedistance(k)computedinthepreviousstep.

�settled=settled[fkg

�successor(k)=i

4.ifsettled6=Vgotostep2

Page 35: (B,E),(C,A),(C,B), V = {A,B,C,D,E}setia/cs310/slides/graph.pdfCS 310 4 ' & $ % More T erminology Simple path {All v ertices are distinct except p ossibly the v 1 and v n. Cycle {path

CS

310

7

'&

$%

D

FE

B

C

A

D

FE

B

C

A

D

FE

B

C

A

D

FE

B

C

A

D

FE

B

C

A

D

FE

B

C

A

Initially

94

4

62

58

3

5

7

94

4

62

58

3

5

7

94

4

62

58

3

5

7

94

4

62

58

3

5

7

Distance(B) = 4 Distance(B) = 4Distance(D) = 8

Distance(B) = 4Distance(D) = 8Distance(C) = 12

Distance(B) = 4

Distance(D) = 8

Distance(C) = 12

94

4

62

58

3

5

7

Distance(E) = 13

Distance(B) = 4

Distance(D) = 8

Distance(C) = 12

Distance(E) = 13Distance(F) = 17

94

4

62

58

3

5

7