A few days after you paint the chess board in
Queen Square, an admirer invites you to the Game Park, where he has a n x n square game board set up. Some of the squares have pieces on them, but most of them are empty. The admirer wants to completely paint some adjacent empty squares such that they form the largest empty square on the game board.
Given the game board as a binary grid with 1=piece and 0=no-piece, what is an O(nē) algorithm to find the largest empty square?
(The notation
O(nē) refers to the algorithm speed for large n.)
Dynamic programming:
call G[x,y] whether there is a peice at x,y. where 1,1 is the lower left corner and n,n is th upper right corner.
We willl create S[x,y] = size of largest open square with upper right corner on x,y.
Call S[0,y]=S[x,0]=0
for x=2 to n
for y=2 to n
if G[x,y] then S[x,y]=0
else S[x,y]=1+min(S[x-1,y-1],S[x-1,y],S[x,y-1])
Now just search S for the largest value (we could easily keep that info around during the generation of S, and if so could be smarter and just keep the n+1 values we need for more space efficiency if so desired).
we visited each square once and did constant work so O(n^2)
|
Posted by Joel
on 2006-11-22 21:51:49 |