Maximal Square

mac2022-06-30  31

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; } };

转载于:https://www.cnblogs.com/deofly/p/maximal-square.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)