动态规划专题

leecode 221

cpp 复制代码
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int n = matrix.size();
        if (n == 0) return 0; // 如果矩阵为空,则直接返回0  
        int m = matrix[0].size();
        vector<vector<int>> ans(n, vector<int>(m, 0)); // 初始化ans为n行m列的二维数组,并全部置为0  
        int maxSideLength = 0;
        // 初始化第一行和第一列  
        for (int i = 0; i < n; i++) {
            ans[i][0] = matrix[i][0] - '0'; // 假设矩阵中的字符是'1'或'0',直接转换为整数  
            maxSideLength = max(maxSideLength, ans[i][0]);
        }
        for (int j = 0; j < m; j++) {
            ans[0][j] = matrix[0][j] - '0';
            maxSideLength = max(maxSideLength, ans[0][j]);
        }


        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (matrix[i][j] == '1') { // 使用'1'字符进行判断,而不是true  
                    ans[i][j] = 1 + min(min(ans[i - 1][j - 1], ans[i][j - 1]), ans[i - 1][j]);
                    maxSideLength = max(maxSideLength, ans[i][j]);
                }
            }
        }
        return maxSideLength * maxSideLength; // 因为返回的是最大正方形的面积,所以需要乘以边长本身  
    }
};

其实这个题目还可以使用二维前缀和来做

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;

int a[101][101];
int b[101][101];

int main() {
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j];
		}
	}
	// 计算前缀和
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			b[i][j] = b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1] + a[i][j];
		}
	}
	int len = 1;
	int ans = 0;
	while (len < min(n, m)) {
		for (int i = len; i <= n; i++) {
			for (int j = len; j <= m; j++) {
				if (b[i][j] - b[i - len][j] - b[i][j - len] + b[i - len][j - len] == len * len) {
					ans = max(ans, len);
				}
			}
		}
		len++;
	}
	cout << ans;
	return 0;
}
相关推荐
数模竞赛Paid answer8 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆8 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
想吃火锅100510 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil20811 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣11 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
qeen8714 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
lucas_AI14 小时前
1.2B 小模型赢过 235B 大模型:NaviDC-OCR 把文档解析卷明白了
人工智能·深度学习·算法
冻柠檬飞冰走茶15 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
民乐团扒谱机15 小时前
【微实验】倒谱算法(Cepstrum)深度解析:原理、数学推导与代码实现
人工智能·算法·语音识别
Nil20816 小时前
leetcode 189轮转数组
数据结构·算法·leetcode