Saturday, January 15, 2011

Brilliant example on dynamic programming


http://www.careercup.com/question?id=2445

Imagine there is a square matrix with n x n cells. Each cell is either filled with a black pixel or a white pixel. Design an algorithm to find the maximum subsquare such that all four borders are filled with black pixels;

white = 0 black = 1
1. construct a row and a col matrix to record the # of consecutive "1" from current node to left, and up, respectively.
e.g.:
Original (A):
11111
11101
10111
01011
row:
12345
12301
10123
01012
col:
11111
22202
30313
01024

int maxsize = 0;
for i=0; ifor j=0; j    if (A[i,j]==1){
	for (int k=min(i,j); k>maxsize; k--){ //min(i,j) is the maximum possible square size from i,j to 0,0 
	   if ((row[i,j] - row[i,j-k] == k) && 
	   (row[i-k,j] - row[i-k,j-k] == k) && 
	   (col[i,j] - col[i-k,j] == k) &&	
	   (col[i-k,j] - col[i-k,j-k] == k) &&
	   )
	   maxsize=k;
	   break;
	}
    }
}

1 comment:

  1. Hi pavan!
    I dont understand the code. Could you explain how we choose the maxsize once we have the row and col matrix?

    ReplyDelete