Interview Question
Country: United States
this is a modification of "Maximum size square sub-matrix with all 1s" DP problem
from www dot geeksforgeeks.org/archives/6257
In the pseudocode, S[i][j] is a size of the maximum square submatrix with all 1s with bottom-right corner (i;j). After computing S[i][j], we only need to remove those squares which are completely contained in large squares
#define R 6
#define C 5
int S[R][C];
int M[R][C] = {
{0, 1, 1, 0, 1},
{1, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{1, 1, 1, 1, 0},
{1, 1, 1, 1, 1},
{0, 0, 0, 0, 0}};
void fillin(int r1, int c1) { // mark overlapping squares
int sz = S[r1][c1], i, j;
int r0 = r1 - sz + 1, c0 = c1 - sz + 1;
for(i = r0; i <= r1; i++)
for(j = c0; j <= c1; j++) {
int s = S[i][j];
if(i - s + 1 >= r0 && j - s + 1 >= c0)
S[i][j] = 0;
}
}
void printMaxSubSquare()
{
int i,j;
int max_of_s, max_i, max_j;
/* Set first column of S[][]*/
for(i = 0; i < R; i++)
S[i][0] = M[i][0];
/* Set first row of S[][]*/
for(j = 0; j < C; j++)
S[0][j] = M[0][j];
/* Construct other entries of S[][]*/
for(i = 1; i < R; i++)
{
for(j = 1; j < C; j++)
{
if(M[i][j] == 1)
S[i][j] = std::min(std::min(S[i][j-1], S[i-1][j]), S[i-1][j-1]) + 1;
else
S[i][j] = 0;
}
}
printf("Input:\n");
for(i = 0; i < R; i++) {
for(j = 0; j < C; j++) {
printf("%d ", M[i][j]);
}
printf("\n\n");
}
int cnt = 0;
for(i = R-1; i >= 0; i--)
for(j = C-1; j >= 0; j--) {
if(S[i][j] <= 0)
continue;
printf("%d: size: %d; bottom-right: (%d; %d)\n", ++cnt, S[i][j], i, j);
fillin(i, j);
}
printf("\n");
}
int main() {
printMaxSubSquare();
}
some results:
Input:
1 1 0 0 1
1 1 1 1 0
1 1 0 1 1
1 1 0 0 1
1: size: 1; bottom-right: (3; 4)
2: size: 2; bottom-right: (3; 1)
3: size: 1; bottom-right: (2; 4)
4: size: 1; bottom-right: (2; 3)
5: size: 2; bottom-right: (2; 1)
6: size: 1; bottom-right: (1; 3)
7: size: 1; bottom-right: (1; 2)
8: size: 2; bottom-right: (1; 1)
9: size: 1; bottom-right: (0; 4)
Input:
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 1 1 0
1 1 1 1 1
0 0 0 0 0
1: size: 1; bottom-right: (4; 4)
2: size: 3; bottom-right: (4; 3)
3: size: 2; bottom-right: (4; 1)
4: size: 1; bottom-right: (1; 3)
5: size: 1; bottom-right: (1; 1)
6: size: 1; bottom-right: (1; 0)
7: size: 1; bottom-right: (0; 4)
8: size: 1; bottom-right: (0; 2)
9: size: 1; bottom-right: (0; 1)
- sqw May 23, 2012