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;
O(n^3) time and O(n^2) space
modified code from http://jeffmeng.com/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-fill/
#include <iostream>
#define MATRIX_WIDTH 5
using namespace std;
const int mmap[MATRIX_WIDTH][MATRIX_WIDTH]=
{
{1,1,1,1,1},
{1,1,1,1,1},
{1,1,1,0,1},
{1,1,1,0,1},
{1,1,1,1,1}
};
void creat_row(int **row)
{
for (int i=0; i<MATRIX_WIDTH; ++i)
{
int val=1;
for (int j=MATRIX_WIDTH-1; j>=0; --j)
{
if (mmap[i][j]==1)
{
row[i][j]=val;
val++;
}
else if(mmap[i][j]==0)
{
row[i][j]=0;
val=1;
}
}
}
}
void creat_col(int *col[])
{
for (int j=0; j<MATRIX_WIDTH; ++j)
{
int val=1;
for (int i=MATRIX_WIDTH-1; i>=0; --i)
{
if (mmap[i][j]==1)
{
col[i][j]=val;
val++;
}
else if(mmap[i][j]==0)
{
col[i][j]=0;
val=1;
}
}
}
}
int find_max(int **row,int **col)
{
int max_sq=0;
int max_x, max_y;
for (int i=0; i+max_sq < MATRIX_WIDTH; i++)
{
for (int j=0; j+max_sq < MATRIX_WIDTH; j++)
{
if (mmap[i][j]==1)
{
max_sq = max(max_sq, 1);
for (int k=min(row[i][j], col[i][j])-1; (k+1) > max_sq; k--)
{
int buttom = i+k;
int right = j+k;
if(mmap[buttom][right] == 1 && row[i+k][j] >= k+1 && col[i][j+k] >= k+1)
{
if(k+1 > max_sq)
{
max_sq = k+1;
max_x = i;
max_y = j;
break;
}
}
}
}
}
}
cout << max_sq << endl;
cout << max_x << " " << max_y << endl;
return max_sq;
}
int find_max ()
{
int **row=new int*[5];
for (int i=0; i<5; ++i) {
row[i]=new int[5];
}
int **col=new int*[5];
for (int i=0; i<5; ++i) {
col[i]=new int[5];
}
creat_row(row);
creat_col(col);
int res=find_max(row, col);
return res;
}
int main()
{
find_max();
return 0;
}