Lecture-12-CS210-2012 (1).pptx
-
Upload
moazzam-hussain -
Category
Documents
-
view
228 -
download
0
Transcript of Lecture-12-CS210-2012 (1).pptx
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
1/44
Data Structures and Algorithms
(CS210/ESO207/ESO211)
Lecture 12
Application of Stack and Queues
Shortest route in a grid with obstacles
8 queens problem
1
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
2/44
Problem 1
Shortest route in a grid with obstacles
2
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
3/44
Shortest route in a grid
From a cell in the grid, we can move to any of its neighboring cell in one step.
From top left corner, find shortest route to each cell avoiding obstacles.
3
3
The input grid is given as a Boolean matrix G such thatG[i,j] = 0 if (i,j) is an obstacle, and 1 otherwise.
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
4/44
Step 1:
Realizing the nontriviality of the problem
4
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
5/44
5
Shortest route in a gridnontriviality of the problem
Definition: Distance of a cell cfrom another cell cis the length (number of steps) of
the shortest route between cand c.
We shall design algorithm for computing distanceof each cell from the start-cell.
As an exercise, you should extend it to a data structure for retrieving shortest route.
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
6/44
Get inspiration from nature
6
Did you ever notice the way ripples on the surface of
watertravel in the presence of obstacles ?
The ripples travels along the shortest route ?
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
7/44
Shortest route in a gridnontriviality of the problem
7
Create a ripple at the start cell and trace
the path it takes to
How to find the shortest route to in the grid?
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
8/44
Shortest route in a gridpropagation of a ripple from the start cell
8
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
9/44
Shortest route in a gridripple reaches cells at distance 1after step 1
9
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
10/44
Shortest route in a gridripple reaches cells at distance 2after step 2
10
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
11/44
Shortest route in a gridripple reaches cells at distance 3after step 3
11
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
12/44
Shortest route in a gridripple reaches cells at distance 8after step 8
12
Watch the next
few slides
carefully.
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
13/44
Shortest route in a gridripple reaches cells at distance 9after step 9
13
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
14/44
Shortest route in a gridripple reaches cells at distance 10after step 10
14
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
15/44
Shortest route in a gridripple reaches cells at distance 11after step 11
15
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
16/44
Shortest route in a gridripple reaches cells at distance 12after step 12
16
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
17/44
Shortest route in a gridripple reaches cells at distance 13after step 13
17
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
18/44
Shortest route in a gridripple reaches cells at distance 14after step 14
18
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
19/44
Shortest route in a gridripple reaches cells at distance 15after step 15
19
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
20/44
Step 2:
Designing algorithm for distances in grid
(using an insight into propagation of ripple)
20
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
21/44
Shortest route in a gridA snapshot of ripple after i steps
: the cells of the grid at distance ifrom the starting cell.
21
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
22/44
Shortest route in a gridA snapshot of the ripple after i+1 steps
22
+
Can We generate
+
from?
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
23/44
How can we generate+from?
Observation: Each cell of +is a neighbor of a cell in . But
every neighbor of may be a cell of or a cell of +.
Question:How to distinguish between a cell of from +?
Key idea: Suppose we initialize Distance[c] of each cell as in the start of the
algorithm; and set Distance[c] appropriately whenever the algorithm visits
(ripple reaches) c. Then just after our algorithm has visited , for every
neighbor b of a cell in ,
Ifb is in ,Distance[b] = ??
Ifb is in +,Distance[b] = ??
23
some number less than
Now can you use the above idea to design
an algorithm to generate +from?
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
24/44
Algorithm to compute +if we know
Compute-next-layer(G, )
{
CreateEmptyList(+);
For each cell cin
For each neighbor bof cwhich is not an obstacle{ if (Distance[b] = )
{ Insert(b, +);
Distance[b] i+1;
}
}
return +;
}
24
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
25/44
The first (not so elegant) algorithm(to compute distance to all cells in the grid)
Distance-to-all-cells(G,0)
{ {0};For(i= 0to ??)
+ Compute-next-layer(G, );
}
The algorithm is not elegant because of
??
Somany temporary lists thatget created.
25
It can be as high as
O()
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
26/44
How to transform the algorithm to an elegant
algorithm ?
Key points we have observed:
We can compute cells at distance i+1if we know all cells up to distance i.
Therefore, we need a mechanism to enumerate the cells of the grid in
non-decreasingorder of distancesfrom the start cell.
26
How to design such a
mechanism ?
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
27/44
Keep a queue Q
27
Q
+
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
28/44
An elegant algorithm(to compute distance to all cells in the grid)
Distance-to-all-cells(G,0)
CreateEmptyQueue(Q);
Distance(0)0;
Enqueue(0,Q);
While( ?? ){ c Dequeue(Q);
For each neighbor bofcwhich is not an obstacle
{ if (Distance(b)= )
{ Distance(b) ?? ;
?? ;
}
}
}
28
NotIsEmptyQueue(Q)
Distance(c) +1
Enqueue(b,Q);
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
29/44
Proof of correctness of algorithm
Question:What is to be proved ?
Answer:At the end of the algorithm,
Distance[c]= the distance of cell c from the starting cell in the grid.
Question:How to prove ?Answer: By the principle of mathematical induction on the distance from the
starting cell.
Inductive assertion:
P(i): The algorithm correctly computes distance to all vertices at distance ifrom the
starting cell.
As an exercise, try to prove P(i) by induction on i.
29
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
30/44
Problem 2
Placing 8 queens safely on a chess board
30
It was explained on the black board. However, for a
better understanding, the slides are also provided here.
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
31/44
8 queen problem
Find a way to place 8 queens on a chess board so that no two of them attack
each other.
31
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
32/44
First some notations and definitions are provided in order
to have a better insight into the problem.
to describe the idea underlying the algorithm compactly.
to describe the algorithm in a formalmanner.
32
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
33/44
A Configurationof 8 queens on chess board
where each row has exactly one queen
Each configuration can be specified by a vector
where is the column number of the queen placed in ith row.
For example, the above configuration can be represented by
33
Q
Q
Q
QQ
Q
Q
Q
1 2 3 4 5 6 7 8
8
7
6
54
3
2
1
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
34/44
Configuration of 8 queens on chess board
where each row has exactly one queen
Lexicographic ordering: We can define a lexicographic ordering among all configurations. For example, appears before
.
Definition: A configuration of 8 queens is a safeconfigurationif no two
queens in the configuration attackeach other.
Aim:To compute a safeconfiguration of 8 queens on a chess board.
34
Most significant digit Least significant digit
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
35/44
To compute a safeconfiguration of 8 queens
A trivial solution: Enumerate all configurations of 8 queens inlexicographic ordering and then search this enumeration for a safe
configuration.
A clever approach: also searches for a safe configuration by exploringconfigurations lexicographically but in a conservativemanner as follows.
Searches for a safeconfiguration in an incremental fashion :
placing queens one by one and cautiously.
As soon as it is realized that a partial configuration is currently unsafeor
will only lead to unsafeconfigurations, it stops, backtracks, and tries the
next potential partial configuration.
(See animation on the following slide to get an idea)
35
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
36/44
A clever approach to search for safeconfiguration
An overview
Place queen of the 1st row in 1stcolumn.
It is unsafeto place second queen at
1stcolumn or 2ndcolumn of 2ndrow.
No need to generate configurations
or .
So we proceed with.
All configurations with
are unsafefor k
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
37/44
A clever approach to search for safeconfiguration
An overview of general step
Let be a safe
configuration of first iqueens.
We try to place queen +in the
leftmost safe position in i+1th row.
If such a position exists, we place +
and proceed to (i+2)th row.
If no safe position exists in i+1th row,
then is unsafe.
To search for the next lexicographic
configuration which will be safe, we
search for the next leftmost safe position
for in ith row.
37
+
8
7
6
5
4
3
2
1
1 2 3 4 5 6 7 8
safe
Because we are enumerating
configurations in lexicographic order
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
38/44
Implementation of the clever approach
An important terminology:
Given a partial configuration of iqueens placed on first irows of the chess,
A queen is said to be safeif it is not attacked by any other queen lying in
any row below it.
A queen is said to be unsafeif it is attacked by at least one queen lying inany row below it.
A queen is uncertainif it is not known yet whether it is safe or unsafe.
Representation of a partial configuration:
Each queen in a partial configuration will be specified by a triplet ,
where rand care the row and column of the cell where the queen is placed.
Flagis a variable which takes one of the values from {safe, unsafe, uncertain }
as explained above.
38
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
39/44
Implementation of the clever approach
A snapshot of the algorithm
At each stage, our algorithm will maintain a partial configuration
where The first iqueens are safe.
The queen at i+1th place will be safe/unsafe/ uncertain
See the following slide for a visual description of a partial configuration at any stage of
our algorithm.
39
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
40/44
Implementation of the clever approach
A snapshot of the algorithm
40
safe
safe/
Unsafe/
uncertain
+
A step taken by our algorithm will depend upon the status of Flag of +.
Our approach of enumerating configurations in lexicographic order hints
at using a suitable data structure effectively. Can you guess it ?
stack S
For queens
+
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
41/44
A single step of the algorithm
Let the stack have queens at present. We take out +.
(Answer the following questions to get a good understanding of the algo)
If+is uncertain: what should be done ?
If+is safe: what should be done ?
If+is unsafe: what should be done ?
41
We determine if it is attacked by any existing queen and change its
status as safeor unsafe accordingly, and push it back into stack.
If = , we are done; otherwise, push +back into the stack and
place a queen in the 1
st
column of ( ) th row and mark it uncertain.
We can shift +to the next available column. But if it was already in
8th column, we mark unsafe.
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
42/44
Finally, The following slide has a simpleand
elegantimplementation of the clever approach
we discussed
42
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
43/44
An elegant algorithm for 8 queens problem
CreateEmptyStack(S);
Push((1,1,safe), S);While(NotIsEmptyStack(S)) do
{ (r,c,flag)Top(S); Pop(S);
3 Cases:
{ Flag is uncertain : If((r,c) does not attack any existing queen) Push((r,c,safe), S);
else Push((r,c,unsafe), S);Flag is safe : If (r= 8) { // we reached a safe configuration of 8 queens
print the solution and empty the stack S;
}
else Push((r+1,1,uncertain), S);
Flag is unsafe : If (c= 8) {
(r,c,flag)Top(S); Pop(S);
Push((r,c,unsafe), S);
}
else Push((r,c+1, uncertain), S);
} 43
-
8/11/2019 Lecture-12-CS210-2012 (1).pptx
44/44
Homework exercises
1. Now that you know the clever algorithm, give reason for pursuing
lexicographic approach in the search of a safeconfiguration by it.
2. Extend the algorithm for computing a safeconfiguration for nqueens on
nby nchess board for any n.
3. The current algorithm finds just one safe configuration. Modify it to
enumerate allsafeconfigurations.
4. If you love programming, implement the cleveralgorithm and trivial
algorithm and see if the clever algorithm is indeed mush faster than the
trivial algorithm.
5. We have given an iterative implementation of the clever algorithm. Canyou design a recursive implementation as well ? Which of them will be
faster in practical implementation, and why ?