标签:
题目要求:
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.
在GeeksforGeeks有一个解决该问题的方法:
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[][]
构造完‘和矩阵S’后,我们只需求得该矩阵的最大值就可以了。
为什么只需求得该最大值就可以了?而且相同的最大值可能有很多个。细想下式我们就会知道‘和矩阵S’中的每一个值表示的都是从其他节点(本结点左上)到本节点所能构成的最大正方形的边长长度。
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
具体的程序如下:
1 class Solution { 2 public: 3 int min(const int a, const int b, const int c) 4 { 5 int minVal = (a < b)?a:b; 6 return (minVal < c)?minVal:c; 7 } 8 9 int maximalSquare(vector<vector<char>>& matrix) { 10 int rows = matrix.size(); 11 if(rows == 0) 12 return 0; 13 14 int cols = matrix[0].size(); 15 if(cols == 0) 16 return 0; 17 18 int maxEdge = 0; 19 vector<vector<int> > sum(rows, vector<int>(cols, 0)); 20 for(int i = 0; i < rows; i++) 21 { 22 if(matrix[i][0] == ‘1‘) 23 { 24 sum[i][0] = 1; 25 maxEdge = 1; 26 } 27 } 28 29 for(int j = 0; j < cols; j++) 30 { 31 if(matrix[0][j] == ‘1‘) 32 { 33 sum[0][j] = 1; 34 maxEdge = 1; 35 } 36 } 37 38 for(int i = 1; i < rows; i++) 39 for(int j = 1; j < cols; j++) 40 { 41 if(matrix[i][j] == ‘0‘) 42 sum[i][j] = 0; 43 else 44 sum[i][j] = min(sum[i-1][j-1], sum[i-1][j], sum[i][j-1]) + 1; 45 46 if(maxEdge < sum[i][j]) 47 maxEdge = sum[i][j]; 48 } 49 50 return maxEdge * maxEdge; 51 } 52 };
LeetCode之“动态规划”:Maximal Square
标签:
原文地址:http://www.cnblogs.com/xiehongfeng100/p/4564382.html