Loading

LeetCode 221. 最大正方形

思路

方法:动态规划

思路来源:

LeetCode官方题解 - 最大正方形

理解 三者取最小+1

 1 class Solution {
 2 public:
 3     int maximalSquare(vector<vector<char>>& matrix) {
 4         if (matrix.size() == 0 || matrix[0].size() == 0) {
 5             return 0;
 6         }
 7         int maxSide = 0;
 8         int rows = matrix.size(), columns = matrix[0].size();
 9         vector<vector<int>> dp(rows, vector<int>(columns));
10         for (int i = 0; i < rows; i++) {
11             for (int j = 0; j < columns; j++) {
12                 if (matrix[i][j] == '1') {
13                     if (i == 0 || j == 0) {
14                         dp[i][j] = 1;
15                     } else {
16                         dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
17                     }
18                     maxSide = max(maxSide, dp[i][j]);
19                 }
20             }
21         }
22         int maxSquare = maxSide * maxSide;
23         return maxSquare;
24     }
25 };

 

posted @ 2021-03-13 20:25  拾月凄辰  阅读(54)  评论(0编辑  收藏  举报