LeetCode: 221. Maximal Square

题目描述

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

解题思路 —— 动态规划

利用动态规划,将 (i, j) 问题转换为 (i-1, j)(i, j-1)(i-1, j-1) 三个子问题。

AC 代码

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int ans = 0;
        
        for(int i = 1; i < matrix.size(); ++i)
        {
            for(int j = 1; j < matrix[i].size(); ++j)
            {
                if(matrix[i][j] == '1')
                {
                    matrix[i][j] = min(min(matrix[i][j-1], matrix[i-1][j]), matrix[i-1][j-1])+1;
                }
            }
        }
        
        for(int i = 0; i < matrix.size(); ++i)
        {
            for(int j = 0; j < matrix[i].size(); ++j)
            {
                ans = max(ans, matrix[i][j]-'0');
            }
        }
        
        return ans*ans;
    }
};