B - Black Square

传送门

题意:

给你一个N*M的方格,每一个格子有两种颜色:黑,白。现在你可以把白色格子涂成黑色,问你需要最少涂多少个白色格子,才能拼出黑色正方形(黑色小格子组合)。

 

思路:

我们只需要初始时候,统计黑色方格的数量,同时从N*M方格中找出来黑色方格的最左、右、上、下边界。然后取长边构成大的黑色正方形。如果这个正方形在N*M的范围中,那么正方形的面积-黑色方格的初始数量就是结果。注意当黑色方格初始为0的时候,结果为1.

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int n,m,t,l=110,r,u=110,d;
int a[110][110];
int main(){
    cin>>n>>m;
    for (int i=1; i<=n; i++) {
        string s;cin>>s;
        for (int j=0; j<s.length(); j++) {
            if (s[j]=='B') {
                t++;
                a[i][j+1]=1;
            }
        }
    }
    for (int i=1; i<=n; i++) {
        for (int j=1; j<=m; j++) {
            if (a[i][j]) {
                l=min(l, j);
                r=max(r, j);
                u=min(u, i);
                d=max(d, i);
            }
        }
    }
    int x=max(r-l+1, d-u+1);
    if(!t) cout<<"1"<<endl;
    else if (n<x||m<x) cout<<"-1"<<endl;
    else cout<<x*x-t<<endl;
}

 

posted @ 2020-05-12 21:15  驿书达  阅读(223)  评论(0)    收藏  举报