Maximal Square

Description:

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 4.

Solution:

class Solution {
public:
	int maximalSquare(vector<vector<char>>& matrix) {
		if (matrix.empty()) return 0;
		auto m = (int)matrix.size();
		auto n = (int)matrix[0].size();
		int maxSize = 0;
		vector<int> pre(n, 0);
		vector<int> cur(n, 0);
		for (int i = 0; i < n; ++i) {
			pre[i] = matrix[0][i]-'0';
			maxSize = max(maxSize, pre[i]);
		}
		for (int i = 1; i < m; ++i) {
			cur[0] = matrix[i][0]-'0';
			maxSize = max(maxSize, cur[0]);
			for (int j = 1; j < n; ++j) {
				if (matrix[i][j] == '1') {
					cur[j] = min(cur[j-1], min(pre[j], pre[j-1]))+1;
					maxSize = max(maxSize, cur[j]);
				} else cur[j] = 0;
			}
			pre = cur;
		}
	return maxSize*maxSize;
	}
};
posted @ 2015-08-25 21:12  影湛  阅读(151)  评论(0编辑  收藏  举报