您的位置:首页 > 职场人生

Geeks 面试题: Maximum size square sub-matrix with all 1s

2014-03-11 07:28 399 查看


Maximum size square sub-matrix with all 1s

Given a binary matrix, find out the maximum size square sub-matrix with all 1s.

For example, consider the below binary matrix.

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

The maximum square sub-matrix with all set bits is

1  1  1
    1  1  1
    1  1  1

Algorithm:

Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottommost
entry in sub-matrix.

1) Construct a sum matrix S[R][C] for the given M[R][C].
     a)	Copy first row and first columns as it is from M[][] to S[][]
     b)	For other entries, use following expressions to construct S[][]
         If M[i][j] is 1 then
            S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
         Else /*If M[i][j] is 0*/
            S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print 
   sub-matrix of M[][]

For the given M[R][C] in above example, constructed S[R][C] would be:

0  1  1  0  1
   1  1  0  1  0
   0  1  1  1  0
   1  1  2  2  0
   1  2  2  3  1
   0  0  0  0  0

The value of maximum entry in above matrix is 3 and coordinates of the entry are (4, 3). Using the maximum value and its coordinates, we can find out the required sub-matrix.
http://www.geeksforgeeks.org/maximum-size-sub-matrix-with-all-1s-in-a-binary-matrix/
本题和Leetcode上的找到最大面积不一样,这里是找最大的正方形。

不过比Leetcode上的那个题目要容易多了。

这里比原网站省内存,由O(m*n)降到O(n).

按要求返回下标,也容易,我们一个二层for循环,一气呵成解决问题:

#include<vector>
using std::vector;
using std::min;
vector<int> maxSubSquare(vector<vector<bool> > &mat)
{
	vector<int> rs(2);
	if (mat.empty()) return rs;

	vector<vector<int> > tbl(2, vector<int>(mat[0].size()));
	for (int i = 0; i < mat[0].size(); i++)
		tbl[0][i] = mat[0][i];

	bool idx = true;
	int max_s = 0;
	for (int i = 1; i < mat.size(); i++)
	{
		tbl[idx][0] = mat[i][0];
		for (int j = 1; j < mat[0].size(); j++)
		{
			if (mat[i][j])
				tbl[idx][j] = 1+min(tbl[!idx][j-1], min(tbl[!idx][j], tbl[idx][j-1]));
			else tbl[idx][j] = 0;

			if (tbl[idx][j] > max_s)
			{
				max_s = tbl[idx][j];
				rs[0] = i, rs[1] = j;
			}
		}
		idx = !idx;
	}
	return rs;//返回最大行和列的下标
}


测试:

int main()
	{
		bool M[6][5] =  
		{{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}};
		vector<vector<bool> > mat(6);
		for (int i = 0; i < 6; i++)
		{
			mat[i].assign(M[i], M[i]+5);
		}
		for (auto x:mat)
		{
			for (auto y:x)
				cout<<y<<" ";
			cout<<endl;
		}

		vector<int> rs = maxSubSquare(mat);
		printf("indices are : (%d, %d)", rs[0], rs[1]);

		system("pause");
		return 0;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: