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

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

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

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

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

Lecture 9Graph Traversal

Euiseong Seo([email protected])

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

2SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

3SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

4SWE2004: Principles in Programming | Spring 2016 | 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

zy

w x

zy

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

5SWE2004: Principles in Programming | Spring 2016 | 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

zy

5

31

7

w x

zy

1

11

1

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

6SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Data Structures for Graphs

§ Assume that a graph G = (V, E) containsn 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Data Structures for Graphs

§ Adjacency lists in lists

1 2

5 43

1 2

5 43

2 5 /1

1 4 /2 5 32 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

9SWE2004: Principles in Programming | Spring 2016 | 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 43

1 2 51 2

2 1 51 2

4 33 4

3 2 41 2

4 2 51 2

33

5 1 21 2

43

1 2

5 43

1 2 51 2

2 51

3 3 41 2

5 41

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

10SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

11SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

12SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Tree Traversal

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

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

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

BFS

s

2

5

4

7

8

3 6 9

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

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

s

2

5

4

7

8

3 6 9

0

UndiscoveredDiscovered

Finished

Queue: s

Top of queue

21

Shortest pathfrom s

2

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

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

s

2

5

4

7

8

3 6 9

0

Queue: s 2

3

1

1

UndiscoveredDiscovered

FinishedTop of queue

3

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

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

s

2

5

4

7

8

3 6 9

0

Queue: s 2 3

5

1

1

1

UndiscoveredDiscovered

FinishedTop of queue

5

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 2 3 5

41

1

1

2

UndiscoveredDiscovered

FinishedTop of queue

4

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

19SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 2 3 5 4

1

1

1

2

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 3 5 4

1

1

1

2

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 3 5 4

1

1

1

2

6

2

UndiscoveredDiscovered

FinishedTop of queue

6

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 5 4 6

1

1

1

2

2

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 4 6

1

1

1

2

2

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 4 6

1

1

1

2

2

83

UndiscoveredDiscovered

FinishedTop of queue

8

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

26SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

7

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

27SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

9

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

28SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

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

29SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

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

30SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

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

31SWE2004: Principles in Programming | Spring 2016 | 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

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 9

1

1

1

2

2

3

3

3

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue: 9

1

1

1

2

2

3

3

3

UndiscoveredDiscovered

FinishedTop of queue

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

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

s

2

5

4

7

8

3 6 9

0

Queue:

1

1

1

2

2

3

3

3

UndiscoveredDiscovered

FinishedTop of queue è Since Queue is empty, STOP!

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

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

DFS§ Similar to Backtracking

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

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

do if edge e is unexplored thenw = opposite(v, e) // return the end point of e distant to vif vertex w is unexplored then

mark e as a discovered edgerecursively call DFS(G, w)

elsemark e as a back edge

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

36SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Connected Components§ Many seemingly complicated problems reduce

to finding connected components• 15-Puzzle

§ Connected components can be found by usingrepetitive 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

38SWE2004: Principles in Programming | Spring 2016 | 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 vertexbefore 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

39SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

40SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

41SWE2004: Principles in Programming | Spring 2016 | 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

ca

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

42SWE2004: Principles in Programming | Spring 2016 | 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

ab

f

Topological Sorting Algorithm

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

43SWE2004: Principles in Programming | Spring 2016 | 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

bf

d

Topological Sorting Algorithm

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

44SWE2004: Principles in Programming | Spring 2016 | 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

fd

Topological Sorting Algorithm

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

45SWE2004: Principles in Programming | Spring 2016 | 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

de

Topological Sorting Algorithm

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

46SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

47SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Topological Sorting Algorithmtopsort(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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Playing with Wheels204 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

50SWE2004: Principles in Programming | Spring 2016 | 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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

Playing with Wheels9.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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

From Dusk Till Dawn9.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 coffin 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 coffin.

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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

53SWE2004: Principles in Programming | Spring 2016 | 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 coffin 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 coffin.

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 - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

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

From Dusk Till Dawn214 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.

Page 55: Lecture 9 Graph Traversal - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

55SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ([email protected])

Unlock the Lock4408 - Unlock the LockAsia - Kuala Lumpur - 2008/2009

Mr. Ferdaus has created a special type of 4-digit lock named� FeruLock� shown in the picture on the left. It always shows a4-digit value and has a specific unlock code (An integer value).The lock is unlocked only when the unlock code is displayed.This unlock code can be made to appear quickly with the help ofsome of the special buttons available with that lock. Each buttonhas a number associated with it. When any of these buttons ispressed, the number associated with that button is added with thedisplayed value and so a new number is displayed. The lockalways uses least significant 4 digits after addition. After creatingsuch a lock, he has found that, it is also very difficult for him to

unlock the Ferulock. As a very good friend of Ferdaus� , your task is to create a program that will help him tounlock the Ferulock by pressing these buttons minimum number of times.

Input

There will be at most 100 test cases. For each test case, there will be 3 numbers: L, U and R where L (0000 ≤L ≤ 9999) represents the current lock code, U (0000 ≤ U ≤ 9999) represents the unlock code and R (1 ≤ R ≤10) represents the number of available buttons. After that, there are R numbers (0≤ RVi ≤9999) in a linerepresenting the value of buttons. The values of L, U, RVi will always be denoted by a four digit number(even if it is by padding with leading zeroes). Input will be terminated when L = U = R = 0.

Output

For each test case, there will be one line of output which represents the serial of output followed by theminimum number of button press required to unlock the lock. If it is not possible to unlock the lock, then printa line � Permanently Locked� instead (without quotes).

Sample Input Output for SampleInput0000 9999 1

1000

0000 9999 1

0001

Case 1: Permanently Locked

Case 2: 9999

Case 3: 48

4408 - Unlock the Lock 1/2

Page 56: Lecture 9 Graph Traversal - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

56SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ([email protected])

Unlock the Lock

InputThere will be at most 100 test cases. For each test case, there will be 3 numbers:L, U and R where L (0000 ≤ L ≤ 9999) represents the current lock code, U(0000 ≤ U ≤ 9999) represents the unlock code and R (1 ≤ R ≤ 10) representsthe number of available buttons. After that, there are R numbers (0≤ RVi≤9999) in a line representing the value of buttons. The values of L, U, RVi willalways be denoted by a four digit number (even if it is by padding with leadingzeroes). Input will be terminated when L = U = R = 0.

OutputFor each test case, there will be one line of output which represents the serial ofoutput followed by the minimum number of button press required to unlock thelock. If it is not possible to unlock the lock, then print a line “PermanentlyLocked” instead (without quotes).

Page 57: Lecture 9 Graph Traversal - csl.skku.educsl.skku.edu/uploads/SWE2004S16/Lecture9.pdf · SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ( euiseong@skku.edu) 1 Lecture

57SWE2004: Principles in Programming | Spring 2016 | Euiseong Seo ([email protected])

Unlock the Lock

Sample Input0000 9999 110000000 9999 100015234 1212 31023 0101 00010 0 0

Output for Sample InputCase 1: Permanently LockedCase 2: 9999Case 3: 48