king's trouble II

本文介绍了一种使用动态规划解决矩阵中寻找最大全为1的正方形子矩阵问题的方法。通过构建一个二维数组来记录每个位置能形成的正方形的最大边长,最终找到整个矩阵中的最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
Long time ago, a king occupied a vast territory.
Now there is a problem that he worried that he want to choose a largest square of his territory to build a palace.
Can you help him?
For simplicity, we use a matrix to represent the territory as follows:
0 0 0 0 0
0 1 0 1 0
1 1 1 1 0
0 1 1 0 0
0 0 1 0 0
Every single number in the matrix represents a piece of land, which is a 1*1 square
1 represents that this land has been occupied
0 represents not
Obviously the side-length of the largest square is 2

Input
The first line of the input contains a single integer t (1≤t≤5) — the number of cases.
For each case
The first line has two integers N and M representing the length and width of the matrix
Then M lines follows to describe the matrix
1≤N,M≤1000

Output
For each case output the the side-length of the largest square

Sample Input
2
5 5
0 0 0 0 0
0 1 0 1 0
1 1 0 1 0
0 1 1 0 0
0 0 1 0 0
5 5
0 0 0 0 0
0 1 0 1 0
1 1 1 1 0
0 1 1 0 0
0 0 1 0 0

Sample Output
1
2

dp

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int a[1010][1010];
int dp[1010][1010];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        memset(dp,0,sizeof(dp));
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<m;j++)
            {
                scanf("%d",&a[i][j]);
            }
        }
        int ans=0;
        for(int i=1;i<n;i++)
        {
            for(int j=1;j<m;j++)
            {
                if(a[i][j]==1)
                {
                    dp[i][j]=min(dp[i][j-1],min(dp[i-1][j-1],dp[i-1][j]))+1;
                }
                 ans=max(ans,dp[i][j]);
            }
        }
        printf("%d\n",ans);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值