题目:
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.
解题思路:
这种包含最大、最小等含优化的字眼时,一般都需要用到动态规划进行求解。本题求面积我们可以转化为求边长,由于是正方形,因此可以根据正方形的四个角的坐标写出动态规划的转移方程式(画一个图,从左上角推到右下角,很容易理解):
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1; where matrix[i][j] == 1
根据此方程,就可以写出如下的代码:
代码展示:
1 #include <iostream>
2 #include <vector>
3 #include <cstring>
4 using namespace std;
5
6 //dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
7 //where matrix[i][j] == 1
8 int maximalSquare(vector<vector<char>>& matrix)
9 {
10 if (matrix.empty())
11 return 0;
12
13 int rows = matrix.size();//行数
14 int cols = matrix[0].size(); //列数
15
16 vector<vector<int> > dp(rows+1, vector<int>(cols+1, 0));
17 /*
18 0 0 0 0 0 0
19 0 1 0 1 0 0
20 0 1 0 1 1 1
21 0 1 1 1 1 1
22 0 1 0 0 1 0
23 */
24 int result = 0; //return result
25
26 for (int i = 0; i < rows; i ++) {
27 for (int j = 0; j < cols; j ++) {
28 if (matrix[i][j] == '1') {
29 int temp = min(dp[i][j], dp[i][j+1]);
30 dp[i+1][j+1] = min(temp, dp[i+1][j]) + 1;
31 }
32 else
33 dp[i+1][j+1] = 0;
34
35 result = max(result, dp[i+1][j+1]);
36 }
37 }
38 return result * result; //get the area of square;
39 }
40
41 // int main()
42 // {
43 // char *ch1 = "00000";
44 // char *ch2 = "00000";
45 // char *ch3 = "00000";
46 // char *ch4 = "00000";
47 // vector<char> veccol1(ch1, ch1 + strlen(ch1));
48 // vector<char> veccol2(ch2, ch2 + strlen(ch2));
49 // vector<char> veccol3(ch3, ch3 + strlen(ch3));
50 // vector<char> veccol4(ch4, ch4 + strlen(ch4));
51 //
52 // vector<vector<char> > vecrow;
53 // vecrow.push_back(veccol1);
54 // vecrow.push_back(veccol2);
55 // vecrow.push_back(veccol3);
56 // vecrow.push_back(veccol4);
57 //
58 // vector<vector<char> > vec;
59 // cout << maximalSquare(vec);
60 // return 0;
61 // }