54
1 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected]) Lecture 9 Graph Traversal Euiseong Seo ([email protected])

Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected]) 1 Lecture

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

1 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Lecture 9 Graph Traversal

Euiseong Seo ([email protected])

Page 2: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

2 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Need for Graphs §  One of unifying themes of computer science §  Closely related to many daily life problems

•  Navigation •  Circuit generation •  Social network services •  Games •  Computer networks

§  How can a problem be represented as a graph? §  How to solve a graph problem?

Page 3: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

3 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Graph Notation §  A graph G = (V, E)

•  V is a set of vertices(nodes) •  E is a set of edges

–  E = (x, y) where x, y ∈ V – Ordered or unordered pairs of vertices from V

§  Modeling of problems – What are vertices and edges in the followings? •  Road networks •  Human interactions •  Program analysis

Page 4: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

4 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Flavors of Graphs §  Undirected or directed

•  A graph is undirected if edge (x, y) ∈ E implies that (y,x) ∈ E, too

•  Otherwise, the graph is directed

w x

z y

w x

z y

Page 5: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

5 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Flavors of Graphs §  Weighted or unweighted

•  If each edge of a graph is assigned a numerical value, or weight, the graph is a weighted graph

•  Otherwise, it is a unweighted graph

w x

z y

5

3 1

7

w x

z y

1

1 1

1

Page 6: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

6 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Flavors of Graphs §  Cyclic or acyclic

•  An acyclic graph does not contain any cycles •  Trees are connected acyclic undirected graphs •  Directed acyclic graphs are called DAGs

Page 7: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

7 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Data Structures for Graphs §  Assume that a graph G = (V, E) contains

n vertices and m edges §  Adjacency matrix

•  Use a n x n matrix M •  M[i,j] = 1, if (i,j) ∈ E •  M[i,j] = 0, if (i,j) ∉ E •  Pros

–  Easy to add or remove edges –  Easy to find a specific edge, (i,j), if exists

•  Cons – Waste of memory space for sparse graphs

Page 8: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

8 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Data Structures for Graphs §  Adjacency lists in lists

1 2

5 4 3

1 2

5 4 3

2 5 / 1

1 4 / 2 5 3

2 4 / 3

2 3 / 4 5

4 2 / 5 1

2 5 / 1

5 / 2

3 4 / 3

4 / 5

Page 9: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

9 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Data Structures for Graphs §  Adjacency lists in matrices

•  Use arrays instead of linked lists •  Looks like it combines the worst properties of both, but.

1 2

5 4 3

1 2 5 1 2

2 1 5 1 2

4 3 3 4

3 2 4 1 2

4 2 5 1 2

3 3

5 1 2 1 2

4 3

1 2

5 4 3

1 2 5 1 2

2 5 1

3 3 4 1 2

5 4 1

Page 10: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

10 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

List in Array Representation

§  An undirected edge (x,y) appears twice, once as y in x’s list and once as x in y’s list

List in Array Representation

For each graph, we keep count of the number of vertices, andassign each vertex a unique number from 1 to nvertices.The edges go in an MAXV ! MAXDEGREE array, so eachvertex can be adjacent to MAXDEGREE others. DefiningMAXDEGREE to be MAXV can be wasteful of space for low-degree graphs:#define MAXV 100 /* maximum number of vertices */#define MAXDEGREE 50 /* maximum vertex outdegree */

typedef struct {int edges[MAXV+1][MAXDEGREE]; /* adjacency info */int degree[MAXV+1]; /* outdegree of each vertex */int nvertices; /* number of vertices in graph */int nedges; /* number of edges in graph */

} graph;

Page 11: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

11 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Reading a Graph

Reading a Graph

A typical graph format consists of an initial line featuringthe number of vertices and edges in the graph, followed bya listing of the edges at one vertex pair per line.read_graph(graph *g, bool directed){

int i; /* counter */int m; /* number of edges */int x, y; /* vertices in edge (x,y) */

initialize_graph(g);scanf("%d %d",&(g->nvertices),&m);for (i=1; i<=m; i++) {

scanf("%d %d",&x,&y);insert_edge(g,x,y,directed);

}}

initialize_graph(graph *g){

int i; /* counter */

g -> nvertices = 0;g -> nedges = 0;for (i=1; i<=MAXV; i++) g->degree[i] = 0;

}

Page 12: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

12 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Inserting an Edge

Inserting an Edge

The critical routine is insert edge. We parameterize itwith a Boolean flag directed to identify whether we needto insert two copies of each edge or only one. Note the use ofrecursion to solve the problem:insert_edge(graph *g, int x, int y, bool directed){

if (g->degree[x] > MAXDEGREE)printf("Warning: insertion(%d,%d) exceeds max degree\n",x,y);

g->edges[x][g->degree[x]] = y;g->degree[x] ++;

if (directed == FALSE)insert_edge(g,y,x,TRUE);

elseg->nedges ++;

}

Page 13: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

13 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Tree Traversal §  BFS (Breadth First Search) §  DFS (Depth First Search)

Page 14: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

14 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

BFS

s

2

5

4

7

8

3 6 9

Page 15: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

15 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Undiscovered Discovered

Finished

Queue: s

Top of queue

2 1

Shortest path from s

2

Page 16: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

16 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: s 2

3

1

1

Undiscovered Discovered

Finished Top of queue

3

Page 17: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

17 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: s 2 3

5

1

1

1

Undiscovered Discovered

Finished Top of queue

5

Page 18: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

18 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 2 3 5

4 1

1

1

2

Undiscovered Discovered

Finished Top of queue

4

Page 19: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

19 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 2 3 5 4

1

1

1

2

5 already discovered: don't enqueue

Undiscovered Discovered

Finished Top of queue

Page 20: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

20 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 2 3 5 4

1

1

1

2

Undiscovered Discovered

Finished Top of queue

Page 21: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

21 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 3 5 4

1

1

1

2

Undiscovered Discovered

Finished Top of queue

Page 22: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

22 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 3 5 4

1

1

1

2

6

2

Undiscovered Discovered

Finished Top of queue

6

Page 23: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

23 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 5 4 6

1

1

1

2

2

Undiscovered Discovered

Finished Top of queue

Page 24: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

24 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 4 6

1

1

1

2

2

Undiscovered Discovered

Finished Top of queue

Page 25: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

25 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 4 6

1

1

1

2

2

8 3

Undiscovered Discovered

Finished Top of queue

8

Page 26: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

26 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 6 8

1

1

1

2

2

3

7

3

Undiscovered Discovered

Finished Top of queue

7

Page 27: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

27 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 6 8 7

1

1

1

2

2

3

9

3

3

Undiscovered Discovered

Finished Top of queue

9

Page 28: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

28 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 8 7 9

1

1

1

2

2

3

9

3

3

Undiscovered Discovered

Finished Top of queue

Page 29: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

29 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 7 9

1

1

1

2

2

3

3

3

Undiscovered Discovered

Finished Top of queue

Page 30: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

30 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 7 9

1

1

1

2

2

3

3

3

Undiscovered Discovered

Finished Top of queue

Page 31: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

31 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 7 9

1

1

1

2

2

3

3

3

Undiscovered Discovered

Finished Top of queue

Page 32: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

32 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 9

1

1

1

2

2

3

3

3

Undiscovered Discovered

Finished Top of queue

Page 33: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

33 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue: 9

1

1

1

2

2

3

3

3

Undiscovered Discovered

Finished Top of queue

Page 34: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

34 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

s

2

5

4

7

8

3 6 9

0

Queue:

1

1

1

2

2

3

3

3

Undiscovered Discovered

Finished Top of queue Since Queue is empty, STOP!

Page 35: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

35 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

DFS §  Similar to Backtracking

•  Go as deep as you can •  Next one is your siblings

§  Stack is an ideal candidate DFS(G, v) for all edges e incident on v

do if edge e is unexplored then w ← opposite(v, e) // return the end point of e

distant to v if vertex w is unexplored then mark e as a discovered edge recursively call DFS(G, w) else mark e as a back edge

Page 36: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

36 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Finding Paths §  BFS Tree from x is unique §  Parent[i] is the node that discovered node i during

the BFS originated from x §  Finding the shortest path from x to y

in a undirected graph •  By following the chain of ancestors backward from y to

the root

Since this is the reverse of how we normally want the path,we can either (1) store it and then explicitly reverse it using astack, or (2) let recursion reverse it for us, as in the followingslick routine:find_path(int start, int end, int parents[]){

if ((start == end) || (end == -1))printf("\n%d",start);

else {find_path(start,parents[end],parents);printf(" %d",end);

}}

Page 37: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

37 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Connected Components §  Many seemingly complicated problems reduce to

finding connected components •  15-Puzzle

§  Connected components can be found by using repetitive application of DFS or BFS

Connected Components Implementation

connected_components(graph *g){

int c; /* component number */int i; /* counter */

initialize_search(g);

c = 0;for (i=1; i<=g->nvertices; i++)

if (discovered[i] == FALSE) {c = c+1;printf("Component %d:",c);dfs(g,i);printf("\n");

}}

Page 38: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

38 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Topological Sorting §  One of the fundamental operations on DAGs §  Construct an ordering of the vertices such that all

directed edges go from left to right •  Cannot exist over cyclic graphs

§  This gives us a way to process each vertex before any of its successors •  Suppose we seek the shortest (or longest) path

from x to y •  No vertex appearing after y in the topological order

can contribute to any such path

Page 39: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

39 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Topological Sorting Algorithm §  Definition

•  A topological sort of a DAG G is a linear ordering of all its vertices such that if G contains a link (u,v), then node u appears before node v in the ordering

b

c a

d

b

c a

d

1

2 3

4

Page 40: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

40 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Topological Sorting Algorithm §  find source nodes (indegree = 0)

•  if there is no such node, the graph is NOT DAG

c

a

b

e

d

f

in_deg=1

in_deg=0

in_deg=2

in_deg=1

in_deg=3

in_deg=1 Queue

Sorted: -

c

Page 41: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

41 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Topological Sorting Algorithm §  span c; decrement in_deg of a, b, e

•  store a in Queue since in_deg becomes 0

c

a

b

e

d

f

in_deg=0

in_deg=0

in_deg=1

in_deg=1

in_deg=2

in_deg=1 Queue

Sorted: c

c a

Page 42: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

42 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

§  span a; decrement in_deg of b, f •  store b, f in Queue since ...

c

a

b

e

d

f

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=2

in_deg=1 Queue

Sorted: c a

a b

f

Topological Sorting Algorithm

Page 43: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

43 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

§  span b; store d in Queue

c

a

b

e

d

f

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=2

in_deg=0 Queue

Sorted: c a b

b f

d

Topological Sorting Algorithm

Page 44: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

44 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

§  span f; decrement in_deg of e •  no node with in_deg = 0 is found

c

a

b

e

d

f

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=1

in_deg=0 Queue

Sorted: c a b f

f d

Topological Sorting Algorithm

Page 45: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

45 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

§  span d; store e in Queue.

c

a

b

e

d

f

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=0 Queue

Sorted: c a b f d

d e

Topological Sorting Algorithm

Page 46: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

46 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

§  span e; Queue is empty

c

a

b

e

d

f

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=0

in_deg=0 Queue

Sorted: c a b f d e

e

Topological Sorting Algorithm

Page 47: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

47 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Topological Sorting Algorithm

Topological Sorting Algorithms

Topological sorting can be performed using DFS.However, a more straightforward algorithm does an analysisof the in-degrees of each vertex in a DAG. Any in-degree 0vertex may safely be placed first in topological order.Deleting its outgoing edges may create new in-degree 0vertices, continuing the process.compute_indegrees(graph *g, int in[]){

int i,j; /* counters */

for (i=1; i<=g->nvertices; i++) in[i] = 0;

for (i=1; i<=g->nvertices; i++)for (j=0; j<g->degree[i]; j++) in[ g->edges[i][j] ] ++;

}

Page 48: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

48 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Topological Sorting Algorithm topsort(graph *g, int sorted[]){

int indegree[MAXV]; /* indegree of each vertex */queue zeroin; /* vertices of indegree 0 */int x, y; /* current and next vertex */int i, j; /* counters */

compute_indegrees(g,indegree);init_queue(&zeroin);for (i=1; i<=g->nvertices; i++)

if (indegree[i] == 0) enqueue(&zeroin,i);

j=0;while (empty(&zeroin) == FALSE) {

j = j+1;x = dequeue(&zeroin);sorted[j] = x;for (i=0; i<g->degree[x]; i++) {

y = g->edges[x][i];indegree[y] --;if (indegree[y] == 0) enqueue(&zeroin,y);

}}

if (j != g->nvertices)printf("Not a DAG -- only %d vertices found\n",j);

}

Page 49: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

49 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Playing with Wheels 204 9. Graph Traversal

9.6.2 Playing With WheelsPC/UVa IDs: 110902/10067, Popularity: C, Success rate: average Level: 2

Consider the following mathematical machine. Digits ranging from 0 to 9 are printedconsecutively (clockwise) on the periphery of each wheel. The topmost digits of thewheels form a four-digit integer. For example, in the following figure the wheels formthe integer 8,056. Each wheel has two buttons associated with it. Pressing the buttonmarked with a left arrow rotates the wheel one digit in the clockwise direction andpressing the one marked with the right arrow rotates it by one digit in the oppositedirection.

We start with an initial configuration of the wheels, with the topmost digits formingthe integer S1S2S3S4. You will be given a set of n forbidden configurations Fi1Fi2Fi3Fi4

(1 ! i ! n) and a target configuration T1T2T3T4. Your job is to write a programto calculate the minimum number of button presses required to transform the initialconfiguration to the target configuration without passing through a forbidden one.

InputThe first line of the input contains an integer N giving the number of test cases. Ablank line then follows.

The first line of each test case contains the initial configuration of the wheels, specifiedby four digits. Two consecutive digits are separated by a space. The next line containsthe target configuration. The third line contains an integer n giving the number of for-bidden configurations. Each of the following n lines contains a forbidden configuration.There is a blank line between two consecutive input sets.

OutputFor each test case in the input print a line containing the minimum number of buttonpresses required. If the target configuration is not reachable print “-1”.

Page 50: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

50 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Playing with Wheels

204 9. Graph Traversal

9.6.2 Playing With WheelsPC/UVa IDs: 110902/10067, Popularity: C, Success rate: average Level: 2

Consider the following mathematical machine. Digits ranging from 0 to 9 are printedconsecutively (clockwise) on the periphery of each wheel. The topmost digits of thewheels form a four-digit integer. For example, in the following figure the wheels formthe integer 8,056. Each wheel has two buttons associated with it. Pressing the buttonmarked with a left arrow rotates the wheel one digit in the clockwise direction andpressing the one marked with the right arrow rotates it by one digit in the oppositedirection.

We start with an initial configuration of the wheels, with the topmost digits formingthe integer S1S2S3S4. You will be given a set of n forbidden configurations Fi1Fi2Fi3Fi4

(1 ! i ! n) and a target configuration T1T2T3T4. Your job is to write a programto calculate the minimum number of button presses required to transform the initialconfiguration to the target configuration without passing through a forbidden one.

InputThe first line of the input contains an integer N giving the number of test cases. Ablank line then follows.

The first line of each test case contains the initial configuration of the wheels, specifiedby four digits. Two consecutive digits are separated by a space. The next line containsthe target configuration. The third line contains an integer n giving the number of for-bidden configurations. Each of the following n lines contains a forbidden configuration.There is a blank line between two consecutive input sets.

OutputFor each test case in the input print a line containing the minimum number of buttonpresses required. If the target configuration is not reachable print “-1”.

Page 51: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

51 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

Playing with Wheels 9.6. Problems 205

Sample Input2

8 0 5 66 5 0 858 0 5 78 0 4 75 5 0 87 5 0 86 4 0 8

0 0 0 05 3 1 780 0 0 10 0 0 90 0 1 00 0 9 00 1 0 00 9 0 01 0 0 09 0 0 0

Sample Output14-1

9.6. Problems 205

Sample Input2

8 0 5 66 5 0 858 0 5 78 0 4 75 5 0 87 5 0 86 4 0 8

0 0 0 05 3 1 780 0 0 10 0 0 90 0 1 00 0 9 00 1 0 00 9 0 01 0 0 09 0 0 0

Sample Output14-1

Page 52: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

52 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

From Dusk Till Dawn 9.6. Problems 213

9.6.7 From Dusk Till DawnPC/UVa IDs: 110907/10187, Popularity: B, Success rate: average Level: 3

Vladimir has white skin, very long teeth and is 600 years old, but this is no problembecause Vladimir is a vampire. Vladimir has never had any problems with being avampire. In fact, he is a successful doctor who always takes the night shift and so hasmade many friends among his colleagues. He has an impressive trick which he loves toshow at dinner parties: he can tell blood group by taste. Vladimir loves to travel, butbeing a vampire he must overcome three problems.

1. He can only travel by train, because he must take his co!n with him. Fortunatelyhe can always travel first class because he has made a lot of money through longterm investments.

2. He can only travel from dusk till dawn, namely, from 6 P.M. to 6 A.M. Duringthe day he has must stay inside a train station.

3. He has to take something to eat with him. He needs one litre of blood per day,which he drinks at noon (12:00) inside his co!n.

Help Vladimir to find the shortest route between two given cities, so that he cantravel with the minimum amount of blood. If he takes too much with him, people askhim funny questions like, “What are you doing with all that blood?”

InputThe first line of the input will contain a single number telling you the number of testcases.

Each test case specification begins with a single number telling you how many routespecifications follow. Each route specification consists of the names of two cities, thedeparture time from city one, and the total traveling time, with all times in hours.Remember, Vladimir cannot use routes departing earlier than 18:00 or arriving laterthan 6:00.

There will be at most 100 cities and less than 1,000 connections. No route takes lessthan 1 hour or more than 24 hours, but Vladimir can use only routes within the 12hours travel time from dusk till dawn.

All city names are at most 32 characters long. The last line contains two city names.The first is Vladimir’s start city; the second is Vladimir’s destination.

OutputFor each test case you should output the number of the test case followed by “Vladimirneeds # litre(s) of blood.” or “There is no route Vladimir can take.”

Page 53: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

53 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

From Dusk Till Dawn

9.6. Problems 213

9.6.7 From Dusk Till DawnPC/UVa IDs: 110907/10187, Popularity: B, Success rate: average Level: 3

Vladimir has white skin, very long teeth and is 600 years old, but this is no problembecause Vladimir is a vampire. Vladimir has never had any problems with being avampire. In fact, he is a successful doctor who always takes the night shift and so hasmade many friends among his colleagues. He has an impressive trick which he loves toshow at dinner parties: he can tell blood group by taste. Vladimir loves to travel, butbeing a vampire he must overcome three problems.

1. He can only travel by train, because he must take his co!n with him. Fortunatelyhe can always travel first class because he has made a lot of money through longterm investments.

2. He can only travel from dusk till dawn, namely, from 6 P.M. to 6 A.M. Duringthe day he has must stay inside a train station.

3. He has to take something to eat with him. He needs one litre of blood per day,which he drinks at noon (12:00) inside his co!n.

Help Vladimir to find the shortest route between two given cities, so that he cantravel with the minimum amount of blood. If he takes too much with him, people askhim funny questions like, “What are you doing with all that blood?”

InputThe first line of the input will contain a single number telling you the number of testcases.

Each test case specification begins with a single number telling you how many routespecifications follow. Each route specification consists of the names of two cities, thedeparture time from city one, and the total traveling time, with all times in hours.Remember, Vladimir cannot use routes departing earlier than 18:00 or arriving laterthan 6:00.

There will be at most 100 cities and less than 1,000 connections. No route takes lessthan 1 hour or more than 24 hours, but Vladimir can use only routes within the 12hours travel time from dusk till dawn.

All city names are at most 32 characters long. The last line contains two city names.The first is Vladimir’s start city; the second is Vladimir’s destination.

OutputFor each test case you should output the number of the test case followed by “Vladimirneeds # litre(s) of blood.” or “There is no route Vladimir can take.”

Page 54: Lecture 9 Graph Traversal - AndroBenchcsl.skku.edu/uploads/SWE2004S13/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo (euiseong@skku.edu) 1 Lecture

54 SWE2004: Principles in Programming | Spring 2013 | Euiseong Seo ([email protected])

From Dusk Till Dawn 214 9. Graph Traversal

Sample Input23Ulm Muenchen 17 2Ulm Muenchen 19 12Ulm Muenchen 5 2Ulm Muenchen10Lugoj Sibiu 12 6Lugoj Sibiu 18 6Lugoj Sibiu 24 5Lugoj Medias 22 8Lugoj Medias 18 8Lugoj Reghin 17 4Sibiu Reghin 19 9Sibiu Medias 20 3Reghin Medias 20 4Reghin Bacau 24 6Lugoj Bacau

Sample OutputTest Case 1.There is no route Vladimir can take.Test Case 2.Vladimir needs 2 litre(s) of blood.

214 9. Graph Traversal

Sample Input23Ulm Muenchen 17 2Ulm Muenchen 19 12Ulm Muenchen 5 2Ulm Muenchen10Lugoj Sibiu 12 6Lugoj Sibiu 18 6Lugoj Sibiu 24 5Lugoj Medias 22 8Lugoj Medias 18 8Lugoj Reghin 17 4Sibiu Reghin 19 9Sibiu Medias 20 3Reghin Medias 20 4Reghin Bacau 24 6Lugoj Bacau

Sample OutputTest Case 1.There is no route Vladimir can take.Test Case 2.Vladimir needs 2 litre(s) of blood.