Codeforces Round #423 B. Black Square

时间:2022-10-08 08:41:16

题目网址:http://codeforces.com/contest/828/problem/B

题目:

Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.

You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet.

The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.

Output

Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.

Examples
input
5 4
WWWW
WWWB
WWWB
WWBB
WWWW
output
5
input
1 2
BB
output
-1
input
3 3
WWW
WWW
WWW
output
1

以第一个例子为例:

Codeforces Round #423 B. Black Square

代码:
 #include <cstdio>
#include <algorithm>
using namespace std;
const int INF=;
int n,m;
int u,d,l,r;//上下左右取值
int a,b;//长宽
int num;//原始黑细胞数量
int len;//正方形边长
char square[][];
void init(){
u=l=INF;
d=r=-INF;
num=;
}
int main(){
init();
scanf("%d%d ",&n,&m);
for (int i=; i<n; i++) {
gets(square[i]);
for (int j=; j<m; j++) {
if(square[i][j]=='B'){
num++;
u=min(u, i);
d=max(d, i);
l=min(l, j);
r=max(r, j);
}
}
}
a=d-u+;
b=r-l+;
len=max(a, b);
if(num==) printf("1\n");
else if(n<len || m<len) printf("-1\n");
else printf("%d\n",len*len-num);
return ;
}