LeetCode: 221_Maximal Square | 二維0-1矩陣中計算包含1的最大正方形的面積 | Medium

林堯彬發表於2020-04-04

題目:

 

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

 

轉載於:https://www.cnblogs.com/bakari/p/5073519.html

相關文章