lecture5 - games, dfs and bfs

33
COMP2230 Introduction to Algorithmics Lecture 6 A/Prof Ljiljana Brankovic Some slides by Y. Lin

Upload: mrzaggy

Post on 04-Jun-2018

238 views

Category:

Documents


0 download

TRANSCRIPT

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 1/33

COMP2230 Introduction toAlgorithmics

Lecture 6

A/Prof Ljiljana Brankovic

Some slides by Y. Lin

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 2/33

Lecture Overview

• Games

• Depth First SearchText Section 4.2

• Breadth First Search

Text Section 4.3

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 3/33

Graphs and Games

• A special game: Nim– Two players, A  and B  

– Pile of n  matchsticks on the table

– Player A starts, taking k matchsticks,where 1  k < n

– Player on next turn may take j  n-k

matchsticks, where 1  j  2k (as well)– Player to take last matchstick wins

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 4/33

Model Nim as a DirectedGraph?

• We may have a lot of options

• Want to model the whole game as a graph:

– What are the nodes?

– What are edges?

– Why directed?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 5/33

Modelling (cont)

• Each node represents currentstate of game.

– ordered pair (i,j)

– i = # sticks on table

–  j = maximum we can remove

• Each valid move is a directed edge

• Start: (n,n-1)

• Node (0,0) is a losing position

– Why?

• We may have a lot ofmoves

• Want to model the whole

game (over time) as agraph:

– What are the nodes?

– What are edges?

– Why directed?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 6/33

Model (cont)

• Graph representing the game of Nim5:4 1:1

3:3

0:0

4:23:2

2:2

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 7/33

Winning and Losing

5:4 1:1

3:3

0:0

4:2 3:2

2:2

• Node (0,0) is a losing position

• Nodes (1,1), (2,2) and (3,3)are all winning positions

because the player canchoose to send opponent to(0,0)

• Node (3,2) is losing because

player has to send opponentto a winning position

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 8/33

Winning and Losing (general)

Winning position• a move exists, which puts your

opponent in a losing position

• A winning node may have manyedges to other winning nodes

•  Just needs one edge to a

losing node.

Losing position

• there is no move thatavoids putting youropponent in a winningposition

Is every position either winning or losing in Nim?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 9/33

Determining a winning position

• Imagine, you want to write the world’s best Nim playingcomputer program....

• Need an algorithm to determine whether a given node (i,j)

is winning.– Usually the starting position

• All you have is the node (i,j) and the rules.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 10/33

More general games

• two players, alternating turns

• symmetric: same rules for each

• deterministic: no chance involved (eg. dice)

• cannot last forever... what does that say about graph?

• No position allows infinite number of legal moves

• Terminal positions - positions allowing no legal moves

• Graph:

– nodes = game states

– directed edges = legal moves

– Labels: win, lose, draw can be assigned to nodes

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 11/33

Labelling strategy

1. Label any terminal positions

often, if you can’t move you lose 

sometimes if you can’t move it’s a draw (eg. chess) 

2. A non-terminal is winning if at least one edge leads to alosing position

3. A non-terminal is losing if all edges lead to winning

positions

4. Any other non-terminal is a draw. (One of it’s successorsmust also be a draw.) Why?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 12/33

Big Games

• Labeling always works.... in principle.

• Consider chess

– state information is very large

– Graph may be extremely  big

– May only want to explore a small section of the graph

– May not want to store whole graph

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 13/33

Searching graphs

• The previous problems were just examples of searching

graphs (topological sort, backtracking, games, etc)

• Goal: visit all nodes in the graph

• Two basic strategies:

– Depth first search• every time you see a new node, stop and go and look

at that node... Will end up far away from “home”node - brave heart approach

– Breadth first search

• look at all the nearest nodes, in the order you foundthem, before expanding out.... Always stay close tothe “home” node - cautious approach

Both work for directed and undirected graphs.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 14/33

Depth-First Search

G = (V,E)Graph can be directed or

undirectedEach node marked visited  or

not-visited

• procedure dfSearch(G)•   for each v   V do•   visit[v ]  false•   for each v   V do•   if !visit [v ] then •   dfs(v )

Time complexity Q(|V|+|E|); Why?Strictly speaking, the complexity

will depend on data structureused to represent the graph

• procedure dfs(v)•   visit [v ]  true•   for each node w  adjacent to v  •   if !visit[w ] then •   dfs(w )

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 15/33

Depth-First Search

DFS gives two differentordering of nodes: the orderin which they are visited andthe order in which theybecome a dead end

• procedure dfSearch(G)•   count1  0•   count2  0•   for each v   V do

•   visit1[v ]  0•   for each v   V do•   if visit1[v ] = 0 then •   dfs(v )

Time complexity Q(|V|+|E|)Why?

• procedure dfs(v)•   count1   count1  + 1•   visit1[v ]  count1•   for each node w  adjacent to v  

•   if visit1[w ] = 0 then •   dfs(w )•   count2   count2  + 1•   visit2[v ]  count2

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 16/33

DFS example

A

B C D E

F G H I J

L MK

A

B C D E

F G H I J

L MK

1,12

2,6

7,5

3,4

4,3

6,2

5,1

8,11

9,10

10,9

11,8

12,7

The black edges arecalled “back” edgesand they connect avertex with itsancestors in the DFStree.

13,13

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 17/33

Data structures?-stack-adjacency lists or adjacency matrix

This algorithm executes a depth-first search beginning at vertex start in agraph with vertices 1, ... , n  and outputs the vertices in the order in whichthey are visited. The graph is represented using adjacency lists; adj [i ] is areference to the first node in a linked list of nodes representing the vertices

adjacent to vertex i . Each node has members ver , the vertex adjacent to i ,and next , the next node in the linked list or null, for the last node in thelinked list. To track visited vertices, the algorithm uses an array visit ; visit[i ]is set to true if vertex i  has been visited or to false if vertex i  has not beenvisited.

Algorithm 4.2.2 Depth-First Search

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 18/33

Input Parameters: adjOutput Parameters: Nonedfs (adj ,start ) {

n  = adj .last

for i  = 1 to nvisit [i ] = false

for i = 1 to nif (!visit[i])

dfs_recurs (adj,i )}

dfs_recurs (adj ,i ) {println (i )visit [i ] = truetrav  = adj [i ]while (trav  != null) {

i  = trav .ver

if (!visit [i ])dfs_recurs (adj ,i )

trav  = trav .next}

}

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 19/33

DFS - treeA

B C D E

F G H I J

L MK

Tree is not necessarily binary

DFS is often used for:

•  spanning trees (notminimum)

• finding connectedcomponents

• analyzing graph structure(is graph acyclic?)

• finding cut vertices

(articulation points)• topological sorting• backtracking

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 20/33

Breadth-first Search

• DFS

– visits the neighbour of neighbour of...

– naturally recursive

– uses stack (possibly implicit) to order nodes

– LIFO• BFS

– visits all neighbours before advancing

– not naturally recursive

– uses a queue of nodes– FIFO

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 21/33

Breadth-First Search

G = (V,E)Graph can be directed or

undirectedEach node marked visited  or

not-visited  

• procedure bfSearch(G)•   for each v   V do•   visit[v ]  false•   for each v   V do•   if !visit[v ] then •   bfs(v )

Time complexityQ

(|V|+|E|)why?

• procedure bfs(G)•   Q  empty-queue

•   visit [v ]  true•   enqueue v  onto Q•   while Q not empty•   u  Q.dequeue•   for each node w  adjacent to u  

•   if !visit[w ] then•   visit[w ]  true•   enqueue w

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 22/33

BFS exampleA

B C D E

F G H I J

L MK

B

A

B C D E

F G H I J

DC E

F G H

K

I

M

J

K ML

The black edges arecalled “cross” edgesand they connectvertices on the sameor adjacent levels in

the BFS trees.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 23/33

Algorithm 4.3.2 Breadth-First Search

This algorithm executes a breadth-first search beginning at vertexstart  in a graph with vertices 1, ... , n  and outputs the vertices in theorder in which they are visited.

The graph is represented using adjacency lists; adj [i ] is areference to the first node in a linked list of nodes representing thevertices adjacent to vertex i . Each node has members ve r, the vertexadjacent to i , and next , a reference to the next node in the linked listor null, for the last node in the linked list.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 24/33

Algorithm 4.3.2 Breadth-First SearchTo track visited vertices, the algorithm uses an array visit ;

visit [i ] is set to true if vertex i  has been visited or to false if vertex i  has not been visited. The algorithm uses an initially empty queue q  to store pending current vertices. The expression

q .enqueue (val )adds val  to q . The expression

q .front ()returns the value at the front of q  but does not remove it. Theexpression

q .dequeue ()removes the item at the front of q . The expression

q .empty ()returns true if q  is empty or false if q  is not empty.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 25/33

Input Parameters: adj ,startOutput Parameters: Nonebfs (adj ,start ) {

n  = adj .lastfor i  = 1 to n

visit [i ] = falsevisit [start ] = trueprintln (start )q .enqueue (start ) // q  is an initially empty queuewhile (!q .empty ()) {

current  = q .front ()q .dequeue ()

trav  = adj [current ]while (trav  != null) {

v  = trav .verif (!visit [v ]) {

visit [v ] = true; println (v ); q .enqueue (v )}trav  = trav .next

}}

}

Modify this algorithm so that it also works for adisconnected graph.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 26/33

Two treesA

B C D E

F G H I J

L MK

A

B C D E

F G H I J

L MK

BFS tree DFS tree

compare edges coming from node A

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 27/33

Uses for Breadth FirstSearch

• Constructing spanningtrees (similar to DFS)

• Finding connectedcomponents (similar toDFS)

• Partial exploration oflarge graphs

• Consider a probleminvolving exploration ofa graph

• Why would we chooseBFS over DFS?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 28/33

BFS vs DFS

• DFS rushes deep into graph, before even exploringnearby options.

• BFS visits nearby neighbours before going deeper.

• Consider a game (like chess):

– BFS considers all options 1 move ahead beforemoving

– DFS makes a move, then another...

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 29/33

Using BFS

• Graph/map colouring

A crazed Knights fan hires you to paint every room intheir house alternatingly red & blue. They don’twant a red room next to another red room nor ablue room next to another blue room

– How could we represent this as a graph?

– How could we test if it was possible to paint thehouse as desired and if so, which rooms to paintwhich colour?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 30/33

BFS graph colouring

• Run BFS

– include “colour” variable 

– could be boolean

– Paint 1st room red (or blue)– All nodes reached by BFS in each

iteration are painted opposite colourto previous iteration

• If we find a node which is already

coloured, it must be opposite to thecurrent colour

• Would DFS work?

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 31/33

Another Example - MAZE

• We shall model a maze as an undirectedgraph, where vertices will be used to

represent starting point, finishing point,dead ends and all points where morethan on path can be taken.

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 32/33

Another Example - MAZE

• Would you use DFS or BFS to get yourself outof the maze? Why?

31 2

10

11 13

5 4

78

12

6 9

31 2

10

11 13

5 4

7

8

12

6 9

8/14/2019 Lecture5 - Games, DFS and BFS

http://slidepdf.com/reader/full/lecture5-games-dfs-and-bfs 33/33

BFS vs DFSDFS BFS

Datastructures

•Stack•Adjacency listsor adjacency matrix

•Queue•Adjacency listsor adjacency matrix

Complexity Q(|V|+|E|) for adj. lists

Q(|V|2) for adj. matrix

Q(|V|+|E|) for adj.

listsQ(|V|2) for adj. matrix

Applications Finding spanning trees,connected components,

cut vertices (articulationpoints), exploring graphs,topological sort,backtracking

Finding spanning trees,connected components,

exploring graphs,shortest path