[WXM] LeetCode 221. Maximal Square C++

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

Approach

  1. 题目大意就是在矩阵种找最大的正方形,动态规划类题,这道题我一开始写了比较多没用的过程,其实可以一步搞定的,也就是取三条边最短+1,这长度就是正方形的长度,然后怎么取呢,我是从底往上推,这样就可以确保某个点的右点和下点以及右下点的边为最短,然后我们再取这三个点最短就是正方形的边长,具体看代码会更好。
  2. 多做多看多思考。

Code

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

你可能感兴趣的:([WXM] LeetCode 221. Maximal Square C++)