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



-----Note-----

In the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).

In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.

In the third example all cells are colored white, so it's sufficient to color any cell black.

Difficulty: EASY

Solutions:
def min_squares(canvas, length, width):

	def find_top():
		for i in range(length):
			for j in range(width):
				if canvas[i][j] == 'B':
					return i
		return -1

	def find_left():
		for j in range(width):
			for i in range(length):
				if canvas[i][j] == 'B':
					return j

	def find_bottom():
		for i in reversed(range(length)):
			for j in range(width):
				if canvas[i][j] == 'B':
					return i

	def find_right():
		for j in reversed(range(width)):
			for i in range(length):
				if canvas[i][j] == 'B':
					return j
	t = find_top()
	if t == -1:
		return 1
	l = find_left()
	b = find_bottom()
	r = find_right()
	painted = 0
	for i in range(t, b + 1):
		for j in range(l, r + 1):
			if canvas[i][j] == 'W':
				painted += 1
	while b - t < r - l:
		if t > 0:
			t -= 1
			painted += r - l + 1
		elif b < length - 1:
			b += 1
			painted += r - l + 1
		else:
			return -1
	while r - l < b - t:
		if l > 0:
			l -= 1
			painted += b - t + 1
		elif r < width - 1:
			r += 1
			painted += b - t + 1
		else:
			return -1
	return painted
(l, w) = map(int, input().split())
canvas = []
for _ in range(l):
	canvas.append(input())
print(min_squares(canvas, l, w))


(n, m) = map(int, input().split())
x = n
a = []
b = []
c = []
co = 0
while x:
	x -= 1
	a.append(input())
for i in range(n):
	for j in range(m):
		if a[i][j] == 'B':
			b.append(i)
			c.append(j)
			co += 1
if n == 1 or m == 1:
	if n == 1:
		r = a[0]
	else:
		r = a
	if r.count('B') > 1:
		print(-1)
	elif r.count('B') == 1:
		print(0)
	else:
		print(1)
elif co == 0:
	print(1)
else:
	l1 = max(b) - min(b) + 1
	l2 = max(c) - min(c) + 1
	if l1 == n and l2 == m and (n == m):
		print(l1 * l1 - len(b))
	elif l1 == n and l2 == m and (n != m):
		print(-1)
	elif l1 > l2:
		if l1 <= m:
			print(l1 * l1 - len(b))
		else:
			print(-1)
	elif l2 <= n:
		print(l2 * l2 - len(b))
	else:
		print(-1)


def load_data():
	(n, m) = list(map(int, input().split()))
	matrix = []
	for i in range(n):
		line = list(input())
		matrix.append(line)
	return (n, m, matrix)

def find_first_occurrence(M, mode):
	length = len(M)
	index_list = list(range(len(M)))
	if mode < 0:
		index_list = index_list[::-1]
	for i in index_list:
		if 'B' in M[i]:
			return i
	return -1

def main():
	(n, m, matrix) = load_data()
	(top, btm, left, right) = [0] * 4
	matrix_t = list(zip(*matrix))
	top = find_first_occurrence(matrix, 1)
	if top == -1:
		print('1')
		return
	btm = find_first_occurrence(matrix, -1)
	left = find_first_occurrence(matrix_t, 1)
	right = find_first_occurrence(matrix_t, -1)
	width = abs(right - left) + 1
	height = abs(top - btm) + 1
	if width > n or height > m:
		print('-1')
		return
	side = max(width, height)
	if width >= height:
		target = [line[left:right + 1] for line in matrix]
		(up, down) = (top, btm)
	else:
		target = matrix[top:btm + 1]
		target = list(zip(*target))
		(up, down) = (left, right)
	res = float('inf')
	for i in range(len(target) - side + 1):
		temp = list(range(i, i + side))
		if up in temp and down in temp:
			count = sum([target[j].count('W') for j in temp])
			res = min(res, count)
	print(res)
main()


(n, m) = list(map(int, input().split()))
matrix = [[] for i in range(n)]
m_left = 101
m_right = 101
m_top = 101
m_bottom = 101
f = False
present_cnt = 0
for i in range(n):
	s = input().strip()
	for j in range(0, len(s)):
		matrix[i].append(s[j])
		if s[j] == 'B':
			present_cnt += 1
			if f == False:
				f = True
				m_left = j
				m_right = j
				m_top = i
				m_bottom = i
			else:
				m_left = min(j, m_left)
				m_right = max(j, m_right)
				m_top = min(i, m_top)
				m_bottom = max(i, m_bottom)
if m_right == 101:
	print(1)
else:
	left_top = [m_top, m_left]
	right_botom = [m_bottom, m_right]
	hight = m_bottom - m_top + 1
	lenght = m_right - m_left + 1
	if hight < lenght:
		diff = lenght - hight
		if n - diff - hight >= 0:
			print(lenght * lenght - present_cnt)
		else:
			print(-1)
	elif hight > lenght:
		diff = hight - lenght
		if m - diff - lenght >= 0:
			print(hight * hight - present_cnt)
		else:
			print(-1)
	else:
		print(hight * hight - present_cnt)


import math as mt
import sys, string
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
(n, m) = M()
l = []
c = 0
for i in range(n):
	l.append(list(input().strip()))
	c += l[-1].count('B')
hb = (-1, -1)
for i in range(n):
	for j in range(m):
		if l[i][j] == 'B':
			hb = (i, j)
			break
lb = (-1, -1)
for i in range(n - 1, -1, -1):
	for j in range(m):
		if l[i][j] == 'B':
			lb = (i, j)
			break
rb = (-1, -1)
for i in range(m - 1, -1, -1):
	for j in range(n):
		if l[j][i] == 'B':
			rb = (j, i)
leftb = (-1, -1)
for i in range(m):
	for j in range(n):
		if l[j][i] == 'B':
			leftb = (j, i)
s = max(abs(lb[0] - hb[0]) + 1, abs(rb[1] - leftb[1]) + 1)
if s > min(n, m):
	print(-1)
else:
	print(s ** 2 - c)


import sys
par = [int(i) for i in str(input()).split()]
(row, col) = (par[0], par[1])
inf = 10 ** 4 + 2
cells = [['W' for i in range(col)] for j in range(row)]
x_min = col
x_max = 0
y_min = row
y_max = 0
all_W = 0
for i in range(row):
	r = list(str(input()))
	for j in range(col):
		if r[j] == 'B':
			all_W = -1
			if i > y_max:
				y_max = i
			if i < y_min:
				y_min = i
			if j > x_max:
				x_max = j
			if j < x_min:
				x_min = j
		cells[i][j] = r[j]

def count(y_min, x_min, y_max, x_max, cells):
	total = 0
	for i in range(y_min, y_max + 1):
		for j in range(x_min, x_max + 1):
			if cells[i][j] == 'W':
				total += 1
	return total
if all_W == 0:
	print(1)
else:
	max1 = x_max - x_min
	max2 = y_max - y_min
	side = max([[max1, 0], [max2, 1]], key=lambda x: x[0])
	ans = -1
	if side[1] == 0:
		if y_min - (max1 - max2) >= 0:
			ans = count(y_min - (max1 - max2), x_min, y_max, x_max, cells)
		if y_max + (max1 - max2) <= row - 1:
			if ans == -1:
				ans = inf
			ans = min(ans, count(y_min, x_min, y_max + (max1 - max2), x_max, cells))
		if ans != -1:
			print(ans)
			sys.exit(0)
	else:
		if x_min - (max2 - max1) >= 0:
			ans = count(y_min, x_min - (max2 - max1), y_max, x_max, cells)
		if x_max + (max2 - max1) <= col - 1:
			if ans == -1:
				ans = inf
			ans = min(ans, count(y_min, x_min, y_max, x_max + (max2 - max1), cells))
		if ans != -1:
			print(ans)
			sys.exit(0)
	if max2 > max1:
		ans = inf
		for x_min_temp in range(max(0, x_max - max2), col - max2):
			ans = min(ans, count(y_min, x_min_temp, y_max, x_min_temp + max2, cells))
		if ans == inf:
			print(-1)
		else:
			print(ans)
		sys.exit(0)
	if True:
		ans = inf
		for y_min_temp in range(max(0, y_max - max1), row - max1):
			ans = min(ans, count(y_min_temp, x_min, y_min_temp + max1, x_max, cells))
		if ans == inf:
			print(-1)
		else:
			print(ans)
		sys.exit(0)


(h, w) = map(int, input().split())
(x0, y0, x1, y1, c) = (101, 101, 0, 0, 0)
for i in range(h):
	s = str(input())
	for j in range(w):
		if s[j] == 'B':
			(x0, y0, x1, y1, c) = (min(x0, j), min(y0, i), max(x1, j), max(y1, i), c + 1)
ans = max(y1 - y0 + 1, x1 - x0 + 1)
if (ans > h) | (ans > w):
	print(-1)
elif x0 == 101:
	print(1)
else:
	print(ans * ans - c)


import traceback
import os
import sys
from io import BytesIO, IOBase
import math
from collections import defaultdict, Counter
from functools import lru_cache
from itertools import accumulate
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def geti():
	return int(input())

def gets():
	return input()

def getil():
	return list(map(int, input().split()))

def getsl():
	return input().split()

def getinps(s):
	inps = s.split()
	m = {'i': geti, 's': gets, 'il': getil, 'sl': getsl}
	if len(inps) == 1:
		return m[s]()
	return [m[k]() for k in inps]

def get2d(nrows, ncols, n=0):
	return [[n] * ncols for r in range(nrows)]

def get_acc(a):
	return list(accumulate(a))

def get_ncr(n, r):
	if n < r:
		return 0
	return math.factorial(n) // (math.factorial(r) * math.factorial(n - r))

def get_npr(n, r):
	if n < r:
		return 0
	return math.factorial(n) // math.factorial(r)
inf = float('inf')
mod = 10 ** 9 + 7

def main():
	(N, M) = getinps('il')
	g = [gets() for _ in range(N)]
	(mnr, mxr) = (inf, -inf)
	(mnc, mxc) = (inf, -inf)
	ans = 0
	for i in range(N):
		for j in range(M):
			if g[i][j] == 'B':
				ans -= 1
				mnr = min(mnr, i)
				mxr = max(mxr, i)
				mnc = min(mnc, j)
				mxc = max(mxc, j)
	if ans == 0:
		return 1
	s = max(abs(mnr - mxr), abs(mnc - mxc)) + 1
	if s > min(N, M):
		return -1
	ans += s * s
	return ans
try:
	ans = main()
	print(ans)
except Exception as e:
	print(e)
	traceback.print_exc()


nmStr = input()
nm = nmStr.split()
n = int(nm[0])
m = int(nm[1])
map = []
for i in range(n):
	map.append(input())
count = 0
top = n
bottom = 0
left = m
right = 0
for row in range(n):
	for col in range(m):
		if map[row][col] == 'B':
			left = min(left, col)
			right = max(right, col)
			top = min(top, row)
			bottom = max(bottom, row)
			count += 1
edge = max(bottom - top + 1, right - left + 1)
if count == 0 and n > 0 and (m > 0):
	print(1)
elif edge > m or edge > n:
	print(-1)
else:
	print(edge * edge - count)


(n, m) = list(map(int, input().split()))
(blacksX, blacksY) = ([], [])
count = 0
for x in range(n):
	inp = input()
	for y in range(m):
		if inp[y] == 'B':
			blacksX.append(x)
			blacksY.append(y)
			count += 1
if len(blacksX) == 0:
	print(1)
else:
	side = max(max(blacksX) - min(blacksX) + 1, max(blacksY) - min(blacksY) + 1)
	if side <= n and side <= m:
		print(side * side - count)
	else:
		print(-1)


def aaa():
	(r, c) = map(int, input().split())
	(rr, cc, stop) = ([], [], 1)
	for ro in range(r):
		for (co, ch) in enumerate(input()):
			if ch == 'B':
				rr.append(ro)
				cc.append(co)
				stop = 0
	if stop:
		return 1
	(rh, cw) = (max(rr) - min(rr) + 1, max(cc) - min(cc) + 1)
	sl = max(rh, cw)
	if sl > r or sl > c:
		return -1
	return sl * sl - len(rr)
print(aaa())


(q, w) = map(int, input().split())
(z, x, c, v) = (-1, -1, -1, -1)
a = []
s = 0
for i in range(0, q):
	e = input()
	if e.count('B') != 0:
		s += e.count('B')
		n = e.find('B')
		m = e.rfind('B')
		if c == -1:
			c = i
		v = i
		if z == -1:
			z = n
		else:
			z = min(z, n)
		x = max(x, m)
	a.append(e)
(z, x) = (x - z + 1, v - c + 1)
if max(z, x) > min(q, w):
	print(-1)
elif x * z == 0:
	print(1)
else:
	print(max(z, x) ** 2 - s)


(n, m) = map(int, input().split())
(minR, minC) = (n, m)
maxR = maxC = 0
cnt = 0
for i in range(0, n):
	s = input()
	for j in range(0, m):
		if s[j] == 'B':
			minR = min(minR, i)
			minC = min(minC, j)
			maxR = max(maxR, i)
			maxC = max(maxC, j)
			cnt += 1
if maxC - minC + 1 > n or maxR - minR + 1 > m:
	print(-1)
elif cnt == 0:
	print(1)
else:
	t = max(maxR - minR, maxC - minC) + 1
	print(t * t - cnt)


l = input().split()
n = int(l[0])
m = int(l[1])
l = []
for i in range(n):
	lo = input()
	l.append(lo)
maxa = 0
count = 0
op = []
for i in range(n):
	for j in range(m):
		if l[i][j] == 'B':
			op.append(j)
			count += 1
	if len(op) == 0:
		continue
	maxa = max(maxa, max(op) - min(op) + 1)
op = []
for i in range(m):
	for j in range(n):
		if l[j][i] == 'B':
			op.append(j)
	if len(op) == 0:
		continue
	maxa = max(maxa, max(op) - min(op) + 1)
if maxa == 0:
	print(1)
	quit()
if n < maxa or m < maxa:
	print(-1)
else:
	print(maxa * maxa - count)


for a in range(1):
	ans1 = 0
	(n, m) = input().split()
	(n, m) = (int(n), int(m))
	length = 0
	listok = []
	for a in range(n):
		listok.append(input())
	coordlist = []
	for y in range(n):
		for x in range(m):
			if listok[y][x] == 'B':
				coordlist.append((x, y))
	maxlength = 0
	maxwidth = 0
	ys = []
	xs = []
	for a in range(len(coordlist)):
		(x, y) = coordlist[a]
		ys.append(y)
		xs.append(x)
	if xs == [] or ys == []:
		print(1)
		break
	maxwidth = max(xs) - min(xs) + 1
	maxlength = max(ys) - min(ys) + 1
	ans = 0
	if maxlength > maxwidth:
		length = maxlength
	else:
		length = maxwidth
	if length > n or length > m:
		print(-1)
		break
	for x in range(max(xs) - (length - 1), max(xs) + 1):
		for y in range(max(ys) - (length - 1), max(ys) + 1):
			if listok[y][x] == 'W':
				ans += 1
	print(ans)


(n, k) = list(map(int, input().split(' ')))
b = []
r = []
c = []
for i in range(n):
	b.append(input())
for i in range(n):
	for j in range(k):
		if b[i][j] == 'B':
			r.append(i)
			c.append(j)
if len(c) == 0:
	print(1)
else:
	maxr = max(r) - min(r)
	maxc = max(c) - min(c)
	size = max(maxc, maxr) + 1
	if size > n or size > k:
		print(-1)
	else:
		print(size ** 2 - len(c))


I = input
(n, m) = map(int, I().split())
board = []
(yup, ydown, xleft, xrigth) = (0, n, 0, m)
for _ in range(n):
	board.append(I())
for row in board:
	if 'B' not in row:
		yup += 1
	else:
		break
for row in board[::-1]:
	if 'B' not in row:
		ydown -= 1
	else:
		break
tr = list(zip(*board))
for row in tr:
	if 'B' not in row:
		xleft += 1
	else:
		break
for row in tr[::-1]:
	if 'B' not in row:
		xrigth -= 1
	else:
		break
if ydown - yup < 0:
	print(1)
elif ydown - yup > m or xrigth - xleft > n:
	print(-1)
else:
	cnt = 0
	for i in range(yup, ydown):
		for j in range(xleft, xrigth):
			if board[i][j] == 'B':
				cnt += 1
	print(max(ydown - yup, xrigth - xleft) ** 2 - cnt)


s = input().split(' ')
n = int(s[0])
m = int(s[1])
ans = -1
up = n
down = 0
left = m
right = 0
have = 0
for i in range(n):
	s = input()
	for j in range(m):
		if s[j] == 'B':
			have += 1
			up = min(up, i)
			down = max(down, i)
			left = min(left, j)
			right = max(right, j)
if have == 0:
	print(1)
elif up <= down and left <= right:
	l = max(down - up + 1, right - left + 1)
	if l <= min(n, m):
		print(l * l - have)
	else:
		print(-1)


(n, m) = map(int, input().split())
a = []
(flag, cnt, max_count) = (0, 0, 0)
(first_index_column, last_index_column) = (-1, -1)
(first_index_string, last_index_string) = (-1, -1)
for i in range(n):
	x = input()
	if x.count('B') > max_count:
		max_count = x.count('B')
	a.append(x)
	if x.count('B') != 0:
		if flag == 0:
			first_index_string = x.index('B')
			last_index_string = m - (x[::-1].index('B') + 1)
			first_index_column = i
			last_index_column = i
			flag = 1
		elif flag == 1:
			if x.index('B') < first_index_string:
				first_index_string = x.index('B')
			if m - (x[::-1].index('B') + 1) > last_index_string:
				last_index_string = m - (x[::-1].index('B') + 1)
			last_index_column = i
column = last_index_column - first_index_column + 1
string = last_index_string - first_index_string + 1
dif_col_str = abs(string) - abs(column)
if column > m or string > n or max_count > n:
	print(-1)
elif first_index_column == -1 and last_index_column == -1:
	print(1)
else:
	for j in range(n):
		if j < first_index_column != 0 and n - 1 - j >= max(column, string):
			continue
		if j < first_index_column:
			cnt += max(column, string) - a[j].count('B')
		elif first_index_column <= j <= last_index_column:
			if a[j].count('B') != 0:
				cnt += max(column, string) - a[j].count('B')
			elif a[j].count('B') == 0:
				cnt += max(column, string)
		elif j > last_index_column and dif_col_str > 0:
			cnt += max(column, string)
			dif_col_str -= 1
	print(cnt)


(n, m) = [int(i) for i in input().split()]
nm = []
for i in range(n):
	nm.append([i for i in input()])
L = []
D = []
count = 0
for i in range(n):
	for j in range(m):
		if nm[i][j] == 'B':
			L.append(i)
			D.append(j)
			count += 1
sizeL = 0
if L:
	sizeL = max(L) - min(L) + 1
sizeD = 0
if D:
	sizeD = max(D) - min(D) + 1
size = max(sizeL, sizeD)
if count == 0:
	size = 1
if size > n or size > m:
	print(-1)
else:
	print(size ** 2 - count)


inp = input()
(n, m) = inp.split()
n = int(n)
m = int(m)
grid = []
top = n
btm = 0
lft = m
rht = 0
allBlackCount = 0
for i in range(0, n):
	inp = input()
	grid.append(inp)
for i in range(0, n):
	for j in range(0, m):
		if grid[i][j] == 'B':
			top = min(top, i)
			btm = max(btm, i)
			lft = min(lft, j)
			rht = max(rht, j)
			allBlackCount += 1
h = btm - top + 1
w = rht - lft + 1
sz = max(h, w)
if allBlackCount == 0:
	print(1)
elif sz > n or sz > m:
	print(-1)
else:
	print(sz * sz - allBlackCount)


def __starting_point():
	(n, m) = list(map(int, input().split()))
	matrix = list()
	minR = n
	minC = m
	maxR = maxC = 0
	count = 0
	for i in range(n):
		s = input()
		for j in range(m):
			if s[j] == 'B':
				minR = min(minR, i)
				maxR = max(maxR, i)
				minC = min(minC, j)
				maxC = max(maxC, j)
				count += 1
	edge = max(maxR - minR + 1, maxC - minC + 1)
	if count == 0:
		print(1)
	elif edge > n or edge > m:
		print(-1)
	else:
		print(edge * edge - count)
__starting_point()


(n, m) = map(int, input().split())
minr = m
maxr = -1
minc = n
maxc = -1
black = 0
for i in range(n):
	line = input()
	for j in range(m):
		if line[j] == 'B':
			black += 1
			if i < minc:
				minc = i
			if i > maxc:
				maxc = i
			if j < minr:
				minr = j
			if j > maxr:
				maxr = j
if black == 0:
	print(1)
else:
	dr = maxr - minr + 1
	dc = maxc - minc + 1
	if dr > dc:
		if dr <= n:
			print(dr * dr - black)
		else:
			print(-1)
	elif dc <= m:
		print(dc * dc - black)
	else:
		print(-1)


(n, m) = map(int, input().split())
L = [input() for _ in range(n)]
C = [[0 for _ in range(m)] for _ in range(n)]
(x1, y1) = (500, 500)
(x2, y2) = (-1, -1)
for i in range(n):
	sa = 0
	for j in range(m):
		if L[i][j] == 'B':
			x1 = min(i, x1)
			x2 = max(i, x2)
			y1 = min(j, y1)
			y2 = max(j, y2)
			sa += 1
		if i > 0:
			C[i][j] += C[i - 1][j]
		C[i][j] += sa
if x2 == -1:
	print(1)
else:
	a = max(x2 - x1, y2 - y1)
	ans = 1000000
	for i in range(n):
		for j in range(m):
			if i + a < n and j + a < m and (i <= x1) and (x2 <= i + a) and (j <= y1) and (y2 <= j + a):
				s = C[i + a][j + a]
				if i > 0:
					s -= C[i - 1][j]
				if j > 0:
					s -= C[i][j - 1]
				if i > 0 and j > 0:
					s -= C[i - 1][j - 1]
				ans = min((a + 1) * (a + 1) - s, ans)
	if ans == 1000000:
		ans = -1
	print(ans)


(n, m) = map(int, input().split())
l = [[e == 'B' for e in input()] for _ in range(n)]
a = b = float('inf')
c = d = -float('inf')
if any(map(any, l)):
	for i in range(n):
		for j in range(m):
			if l[i][j]:
				a = min(a, i)
				b = min(b, j)
				c = max(c, i)
				d = max(d, j)
	while c != n - 1 and c - a < d - b:
		c += 1
	while a != 0 and c - a < d - b:
		a -= 1
	while d != m - 1 and c - a > d - b:
		d += 1
	while b != 0 and c - a > d - b:
		b -= 1
	if c - a != d - b:
		print(-1)
		exit()
	cnt = 0
	for i in range(a, c + 1):
		for j in range(b, d + 1):
			if not l[i][j]:
				cnt += 1
	print(cnt)
else:
	print(1)


import sys

def input():
	return sys.stdin.readline().rstrip('\n')
(n, m) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(input())
position_of_B = []
for i in range(n):
	for j in range(m):
		if mat[i][j] == 'B':
			position_of_B.append([i, j])
if len(position_of_B) == 0:
	print(1)
else:
	(min_row, max_row, min_col, max_col) = (pow(10, 10), 0, pow(10, 10), 0)
	for [r, c] in position_of_B:
		min_row = min(min_row, r)
		max_row = max(max_row, r)
		min_col = min(min_col, c)
		max_col = max(max_col, c)
	size = max(max_row - min_row + 1, max_col - min_col + 1)
	if size > n or size > m:
		print(-1)
	else:
		print(size * size - len(position_of_B))


(n, m) = map(int, input().split())
matr = [list(input()) for i in range(n)]
h1 = h2 = w1 = w2 = -1
cout = 0
for (i, x) in enumerate(matr):
	for (j, y) in enumerate(x):
		if y == 'B':
			if h1 == -1:
				h1 = h2 = i
				w1 = w2 = j
			else:
				h2 = i
				if j < w1:
					w1 = j
				if j > w2:
					w2 = j
			cout += 1
res = max(h2 - h1 + 1, w2 - w1 + 1)
if res > n or res > m:
	print(-1)
else:
	print(res * res - cout)


(n, m) = map(int, input().split())
field = [input() for _ in range(n)]
ranges = [[m, -1], [n, -1]]
for i in range(n):
	for j in range(m):
		if field[i][j] == 'B':
			ranges[0][0] = min(j, ranges[0][0])
			ranges[0][1] = max(j, ranges[0][1])
			ranges[1][0] = min(i, ranges[1][0])
			ranges[1][1] = max(i, ranges[1][1])
dimX = ranges[0][1] - ranges[0][0] + 1
dimY = ranges[1][1] - ranges[1][0] + 1
if -1 in ranges[0]:
	print(1)
elif dimX > n or dimY > m:
	print(-1)
else:
	if dimX > dimY:
		cnt = dimX * (dimX - dimY)
	else:
		cnt = dimY * (dimY - dimX)
	for i in range(ranges[1][0], ranges[1][1] + 1):
		for j in range(ranges[0][0], ranges[0][1] + 1):
			if field[i][j] == 'W':
				cnt += 1
	print(cnt)


(h, w) = map(int, input().split())
(x0, y0, x1, y1, c) = (1000, 1000, -1, -1, 0)
for i in range(h):
	row = str(input())
	for j in range(w):
		if row[j] == 'B':
			(x0, y0, x1, y1, c) = (min(x0, i), min(y0, j), max(x1, i), max(y1, j), c + 1)
ln = max(x1 - x0 + 1, y1 - y0 + 1)
if ln > min(h, w):
	print(-1)
elif x1 == -1:
	print(1)
else:
	print(ln * ln - c)


class CodeforcesTask828BSolution:

	def __init__(self):
		self.result = ''
		self.n_m = []
		self.square = []

	def read_input(self):
		self.n_m = [int(x) for x in input().split(' ')]
		for x in range(self.n_m[0]):
			self.square.append(input())

	def process_task(self):
		bxmax = bymax = 0
		bxmin = bymin = max(self.n_m) + 1
		blacks = 0
		for x in range(self.n_m[0]):
			for y in range(self.n_m[1]):
				if self.square[x][y] == 'B':
					blacks += 1
					bxmin = min(bxmin, x)
					bxmax = max(bxmax, x)
					bymin = min(bymin, y)
					bymax = max(bymax, y)
		side = 1 + max(bxmax - bxmin, bymax - bymin)
		if side > min(self.n_m):
			self.result = '-1'
		elif side < 0:
			self.result = '1'
		else:
			self.result = str(side ** 2 - blacks)

	def get_result(self):
		return self.result
Solution = CodeforcesTask828BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())


(n, m) = map(int, input().split())
line = [None] * n
for i in range(n):
	line[i] = input()
up = down = left = right = -1
for i in range(n):
	if 'B' in line[i]:
		up = i
		break
for i in range(n):
	if 'B' in line[~i]:
		down = n + ~i
		break
for i in range(m):
	is_found = False
	for j in range(n):
		if line[j][i] == 'B':
			left = i
			is_found = True
			break
	if is_found:
		break
for i in range(m):
	is_found = False
	for j in range(n):
		if line[j][~i] == 'B':
			right = m + ~i
			is_found = True
			break
	if is_found:
		break
height = down - up + 1
width = right - left + 1
count = 0
if height > m or width > n:
	count = -1
elif up == down == left == right == -1:
	count = 1
else:
	for i in range(up, down + 1):
		for j in range(left, right + 1):
			if line[i][j] == 'W':
				count += 1
	extra = 0
	if height > width:
		extra = (height - width) * height
	else:
		extra = (width - height) * width
	count += extra
print(count)


(n, m) = map(int, input().split())
field = [input() for _ in range(n)]
flag = False
(minx, miny) = (101, 101)
(maxx, maxy) = (-1, -1)
for i in range(n):
	for j in range(m):
		if field[i][j] == 'B':
			flag = True
			minx = min(minx, i)
			miny = min(miny, j)
			maxx = max(maxx, i)
			maxy = max(maxy, j)
if not flag:
	print(1)
	exit(0)
if max(maxx - minx, maxy - miny) >= n or max(maxx - minx, maxy - miny) >= m:
	print(-1)
	exit(0)
ans = 0
l = max(maxx - minx, maxy - miny)
for i in range(maxx, maxx - l - 1, -1):
	for j in range(maxy, maxy - l - 1, -1):
		if field[i][j] == 'W':
			ans += 1
print(ans)


def int_map():
	return map(int, input().split(' '))
(n, m) = int_map()
res = 0
ml = -1
mr = -1
mu = -1
md = -1
canv = []
for i in range(n):
	b = input()
	canv.append(b)
	for (x, j) in enumerate(b):
		if j == 'B':
			if ml != -1:
				ml = min(x, ml)
			else:
				ml = x
			if mr != -1:
				mr = max(x, mr)
			else:
				mr = x
			if mu != -1:
				mu = min(i, mu)
			else:
				mu = i
			if md != -1:
				md = max(i, md)
			else:
				md = i
ed = max(mr - ml + 1, md - mu + 1)
if ml == -1:
	print(1)
	exit()
while ml > 0 and mr - ml + 1 < ed:
	ml -= 1
while mr < m - 1 and mr - ml + 1 < ed:
	mr += 1
while mu > 0 and md - mu + 1 < ed:
	mu -= 1
while md < n - 1 and md - mu + 1 < ed:
	md += 1
if mr - ml + 1 != ed or md - mu + 1 != ed:
	print(-1)
	exit()
for i in range(mu, md + 1):
	res += canv[i].count('W', ml, mr + 1)
print(res)


from sys import stdin
(n, m) = [int(i) for i in stdin.readline().split(' ')]
trim = lambda s: s[:-1] if s[-1] == '\n' else s
cells = []
for i in range(0, n):
	cells.append(trim(stdin.readline()))
possible = True
rightColumn = -1
bottomRow = -1
leftColumn = -1
topRow = -1
for i in range(0, m):
	if 'B' in [j[-(i + 1)] for j in cells]:
		leftColumn = m - i - 1
	if 'B' in [j[i] for j in cells]:
		rightColumn = i
for i in range(0, n):
	if 'B' in cells[i]:
		bottomRow = i
	if 'B' in cells[-(i + 1)]:
		topRow = n - i - 1
sidelength = max(rightColumn - leftColumn + 1, bottomRow - topRow + 1)
ans = sidelength ** 2
if topRow == -1:
	ans = 1
if sidelength > n or sidelength > m:
	possible = False
for i in range(topRow, bottomRow + 1):
	for j in range(leftColumn, rightColumn + 1):
		if cells[i][j] == 'B':
			ans -= 1
if possible:
	print(ans)
else:
	print(-1)


(n, m) = map(int, input().split())
s = [list(input()) for _ in range(n)]
(u, d, l, r) = (11 ** 11, 0, 11 ** 11, 0)
for i in range(n):
	for j in range(m):
		if s[i][j] == 'B':
			if i < u:
				u = i
			if i > d:
				d = i
			if j < l:
				l = j
			if j > r:
				r = j
if r - l >= n or d - u >= m:
	print(-1)
elif u == 11 ** 11 and d == 0 and (l == 11 ** 11) and (r == 0):
	print(1)
else:
	ans = 0
	for i in range(u, d + 1):
		for j in range(l, r + 1):
			if s[i][j] == 'W':
				ans += 1
	print(ans + (max(r - l + 1, d - u + 1) - min(r - l + 1, d - u + 1)) * max(r - l + 1, d - u + 1))


(a, b) = map(int, input().split())
m = [[0 for i in range(b)] for j in range(a)]
l = b
r = -1
v = -1
k = 0
for i in range(a):
	p = input()
	for j in range(b):
		m[i][j] = p[j]
for i in range(a):
	for j in range(b):
		if m[i][j] == 'B':
			if v == -1:
				v = i
			n = i
			k += 1
			if l > j:
				l = j
			if r < j:
				r = j
if k == 0:
	print(1)
else:
	s = max(n - v, r - l) + 1
	if s > a or s > b:
		print(-1)
	else:
		print(s * s - k)


(n, m) = list(map(int, input().split()))
sq = [list(input()) for _ in range(n)]
rmin = n
rmax = 0
cmin = m
cmax = 0
cnt = 0
for r in range(n):
	for c in range(m):
		if sq[r][c] == 'B':
			cnt += 1
			rmin = min(rmin, r)
			rmax = max(rmax, r)
			cmin = min(cmin, c)
			cmax = max(cmax, c)
l = max(max(rmax - rmin + 1, cmax - cmin + 1), 1)
if min(n, m) < l:
	ans = -1
else:
	ans = l * l - cnt
print(ans)


(n, m) = [int(i) for i in input().split()]
h = 0
w = 0
s = 0
c = 0
a = 0
minH_ind = 101
maxH_ind = -1
minW_ind = 101
maxW_ind = -1
for i in range(n):
	row = input()
	if row.count('B') > 0:
		a += row.count('B')
		minH_ind = min(i, minH_ind)
		maxH_ind = max(i, maxH_ind)
		c = row.find('B')
		minW_ind = min(minW_ind, c)
		c = row.rfind('B')
		maxW_ind = max(maxW_ind, c)
h = maxH_ind - minH_ind + 1
w = maxW_ind - minW_ind + 1
if a == 0:
	print(1)
elif pow(max(h, w), 2) > n * m or w > n or w > m or (h > n) or (h > m):
	print(-1)
else:
	s = pow(max(h, w), 2)
	c = s - a
	print(c)


(length, width) = map(int, input().strip().split())
(left, right, up, down) = (101, -1, 101, -1)
count = 0
for i in range(length):
	string = input()
	for j in range(width):
		if string[j] == 'B':
			count += 1
			left = min(left, j)
			right = max(right, j)
			up = min(up, i)
			down = max(down, i)
if count == 0:
	print('1')
elif right - left + 1 > min(length, width) or down - up + 1 > min(length, width):
	print('-1')
else:
	square_width = max(right - left + 1, down - up + 1)
	print(square_width ** 2 - count)
area = length * width


(n, m) = map(int, input().split())
a = []
c = 0
minsa = n
maxsa = 0
maxso = 0
minso = m
for i in range(n):
	a.append(input())
for i in range(len(a)):
	for j in range(len(a[i])):
		if a[i][j] == 'B':
			c += 1
			if i < minsa:
				minsa = i
			if i > maxsa:
				maxsa = i
			if j < minso:
				minso = j
			if j > maxso:
				maxso = j
r = max(maxso - minso + 1, maxsa - minsa + 1)
if r <= m and r <= n:
	if c != 0 and c != 1:
		print(r * r - c)
	if c == 0:
		print(1)
	if c == 1:
		print(0)
else:
	print(-1)


def main():
	(n, m) = (int(x) for x in input().split())
	L = [None] * n
	for i in range(n):
		L[i] = input()
	print(solver(n, m, L))

def solver(n, m, L):
	tr = topRow(n, m, L)
	if tr == -1:
		return 1
	br = bottomRow(n, m, L)
	lc = leftCol(n, m, L)
	rc = rightCol(n, m, L)
	colSize = rc - lc + 1
	rowSize = br - tr + 1
	if colSize > n or rowSize > m:
		return -1
	if colSize > rowSize:
		if br >= colSize:
			squareTop = br - colSize + 1
			squareBottom = br
		else:
			squareTop = 0
			squareBottom = colSize - 1
		squareLeft = lc
		squareRight = rc
	elif colSize < rowSize:
		if rc >= rowSize:
			squareLeft = rc - rowSize + 1
			squareRight = rc
		else:
			squareLeft = 0
			squareRight = rowSize - 1
		squareTop = tr
		squareBottom = br
	else:
		squareTop = tr
		squareBottom = br
		squareLeft = lc
		squareRight = rc
	count = 0
	for i in range(squareTop, squareBottom + 1):
		for j in range(squareLeft, squareRight + 1):
			if L[i][j] == 'W':
				count += 1
	return count

def topRow(n, m, L):
	for i in range(n):
		if 'B' in L[i]:
			return i
	return -1

def bottomRow(n, m, L):
	for i in range(n - 1, -1, -1):
		if 'B' in L[i]:
			return i
	return -1

def leftCol(n, m, L):
	for j in range(m):
		for i in range(n):
			if L[i][j] == 'B':
				return j
	return -1

def rightCol(n, m, L):
	for j in range(m - 1, -1, -1):
		for i in range(n):
			if L[i][j] == 'B':
				return j
	return -1
grid1 = [['W', 'W', 'W', 'W'], ['W', 'W', 'W', 'B'], ['W', 'W', 'W', 'B'], ['W', 'W', 'B', 'B'], ['W', 'W', 'W', 'W']]
main()


(n, m) = map(int, input().split())
pole = list()
(min_i, min_j, max_i, max_j) = (n, m, -1, -1)
count_B = 0
for i in range(n):
	pole += [input()]
	for j in range(m):
		t = pole[i][j]
		if t == 'B':
			count_B += 1
			(min_i, min_j, max_i, max_j) = (min(i, min_i), min(j, min_j), max(i, max_i), max(j, max_j))
(d_i, d_j) = (max_i - min_i, max_j - min_j)
side = max(d_i + 1, d_j + 1)
print(1) if count_B == 0 else print(side ** 2 - count_B) if side <= min(n, m) else print(-1)


(n, m) = map(int, input().split())
c = 0
(maxX, maxY, minX, minY) = (-1, -1, n, m)
for x in range(n):
	i = input()
	if 'B' in i:
		minX = min(minX, x)
		maxX = max(maxX, x)
		minY = min(minY, i.index('B'))
		maxY = max(maxY, m - 1 - i[::-1].index('B'))
		c += i.count('B')
l = max(maxX - minX, maxY - minY) + 1
if l > m or l > n:
	print(-1)
elif c == 0:
	print(1)
else:
	print(l ** 2 - c)


(n, m) = list(map(int, input().split()))
ls = []
for i in range(n):
	l = list(str(input()))
	ls.append(l)
minr = 1000
maxr = -1
minc = 1000
maxc = -1
c = 0
for i in range(n):
	for j in range(m):
		if ls[i][j] == 'B':
			c += 1
			if minr > i:
				minr = i
			if maxr < i:
				maxr = i
			if minc > j:
				minc = j
			if maxc < j:
				maxc = j
if c == 0:
	print(1)
	return
elif c == 1:
	print(0)
	return
else:
	a = max(maxr - minr + 1, maxc - minc + 1)
	if a > m or a > n:
		print(-1)
		return
	else:
		print(a * a - c)
		return


(n, m) = map(int, input().split())
a = []
for i in range(n):
	t = input()
	a.append(t)
L = m
R = 0
U = n
D = 0
num = 0
for i in range(n):
	for j in range(m):
		if a[i][j] == 'B':
			num += 1
			L = min(L, j)
			R = max(R, j)
			U = min(U, i)
			D = max(D, i)
len = D - U + 1
wid = R - L + 1
subL = U - 0 + (n - D - 1)
subW = L - 0 + (m - R - 1)
flag = 1
if len > wid:
	sub = len - wid
	if sub <= L:
		L -= sub
	else:
		sub -= L
		L = 0
		if sub <= m - R - 1:
			R += sub
		else:
			flag = 0
elif len < wid:
	sub = wid - len
	if sub <= U:
		U -= sub
	else:
		sub -= U
		U = 0
		if sub <= n - D - 1:
			D += sub
		else:
			flag = 0
if flag:
	if num == 0:
		L = 0
		R = 0
		U = 0
		D = 0
	ans = 0
	i = U
	while i <= D:
		j = L
		while j <= R:
			if a[i][j] == 'W':
				ans += 1
			j += 1
		i += 1
	print(ans)
else:
	print(-1)


(n, m) = map(int, input().split())
T = [[] for i in range(n)]
for i in range(n):
	a = list(input())
	T[i] = a
INF = float('inf')
(minX, maxX) = (INF, 0)
(minY, maxY) = (INF, 0)
cnt = 0
for i in range(n):
	for j in range(m):
		if T[i][j] == 'B':
			minX = min(minX, i)
			maxX = max(maxX, i)
			minY = min(minY, j)
			maxY = max(maxY, j)
			cnt += 1
len = max(maxX - minX + 1, maxY - minY + 1)
if cnt == 0:
	print(1)
elif len <= n and len <= m:
	print(len * len - cnt)
else:
	print(-1)


(n, m) = map(int, input().split())
gf = 100000
gl = 0
vf = 100000
vl = 0
L = [input() for i in range(n)]
for i in range(n):
	r = L[i].find('B')
	if r != -1:
		vf = min(vf, i)
		vl = max(vl, i)
		gf = min(gf, r)
		r1 = L[i].rfind('B')
		gl = max(gl, r1)
so = max(vl - vf + 1, gl - gf + 1)
if so < 0:
	print(1)
	exit()
if so > n or so > m:
	print(-1)
	exit()
k = 0
for i in range(vf, vl + 1):
	for j in range(gf + 1, gl + 2):
		if L[i][j - 1] == 'B':
			k += 1
print(so ** 2 - k)


(a, b) = map(int, input().split())
(l, r) = (b, -1)
(d, u) = (a, -1)
z = []
ok = 1
for i in range(a):
	k = input()
	z.append(k)
	for j in range(b):
		if 'B' in k:
			ok = 0
			l = min(l, k.find('B'))
			r = max(r, k.rfind('B'))
			d = min(d, i)
			u = max(u, i)
if ok:
	print(1)
else:
	h = u - d + 1
	w = r - l + 1
	dim = max(h, w)
	if dim > min(a, b):
		print(-1)
	else:
		s = (dim - min(h, w)) * dim
		for i in range(d, u + 1):
			for j in range(l, r + 1):
				s += 0 + (z[i][j] == 'W')
		print(s)


(n, m) = list(map(int, input().split()))
rows = []
b = 0
(ymin, ymax, xmin, xmax) = (n - 1, 0, m - 1, 0)
for i in range(n):
	row = input()
	for j in range(m):
		if row[j] == 'B':
			b += 1
			if j > xmax:
				xmax = j
			if j < xmin:
				xmin = j
	rows.append(row)
for i in range(m):
	for j in range(n):
		if rows[j][i] == 'B':
			if j > ymax:
				ymax = j
			if j < ymin:
				ymin = j
xlen = xmax - xmin + 1
ylen = ymax - ymin + 1
if xlen > n or ylen > m:
	print(-1)
elif b == 0:
	print(1)
else:
	print(max(xlen, ylen) * max(xlen, ylen) - b)


sheet = []
nm = input().split(' ')
n = int(nm[0])
m = int(nm[1])
countB = 0
minr = minc = 101
maxr = maxc = -1
for i in range(n):
	sheet.append(input())
	for j in range(len(sheet[i])):
		if sheet[i][j] == 'B':
			countB += 1
			if i < minr:
				minr = i
			if i > maxr:
				maxr = i
			if j < minc:
				minc = j
			if j > maxc:
				maxc = j
if minr == 101 and maxr == -1:
	print(1)
else:
	L = 0
	if maxr - minr + 1 > maxc - minc + 1:
		L = maxr - minr + 1
	else:
		L = maxc - minc + 1
	if L > n or L > m:
		print(-1)
	else:
		size = L * L
		print(size - countB)


from sys import stdin, stdout
(n, m) = (int(i) for i in stdin.readline().split())
(x1, x2, y1, y2) = (10 ** 6, 0, 0, 0)
c = 0
flag = False
for i in range(n):
	st = stdin.readline()
	if st.count('B') > 0:
		c += st.count('B')
		if not flag:
			y1 = i
		flag = True
		if x1 > st.index('B'):
			x1 = st.index('B')
		if x2 < st.rindex('B') + 1:
			x2 = st.rindex('B') + 1
		y2 = i + 1
height = y2 - y1
widht = x2 - x1
if c == 0:
	stdout.write('1')
elif max(widht, height) > min(n, m):
	stdout.write('-1')
else:
	stdout.write(str(max(widht, height) ** 2 - c))


def solve(n, m, arr):
	b_cells = []
	for row in range(n):
		for col in range(m):
			if arr[row][col] == 'B':
				b_cells.append((row, col))
	if len(b_cells) < 2:
		return 1 - len(b_cells)
	top = b_cells[0][0]
	right = b_cells[0][1]
	bottom = b_cells[0][0]
	left = b_cells[0][1]
	for cell in b_cells:
		if cell[1] < left:
			left = cell[1]
		elif cell[1] > right:
			right = cell[1]
		if cell[0] < top:
			top = cell[0]
		elif cell[0] > bottom:
			bottom = cell[0]
	square_len = max(bottom - top, right - left) + 1
	new_top = max(bottom - square_len + 1, 0)
	new_left = max(right - square_len + 1, 0)
	new_right = new_left + square_len - 1
	new_bottom = new_top + square_len - 1
	if new_right >= m or new_bottom >= n:
		return -1
	count = 0
	for row in range(new_top, new_bottom + 1):
		for col in range(new_left, new_right + 1):
			if arr[row][col] == 'W':
				count += 1
	return count
(n, m) = map(int, input().split())
arr = []
for i in range(n):
	arr.append(input())
print(solve(n, m, arr))


(n, m) = [int(i) for i in input().split()]
b = 0
u = n
d = 0
l = m
r = 0
count = 0
for x in range(n):
	word = input()
	val = word.count('B')
	pos = word.find('B')
	while pos != -1:
		if val > 0 and pos < l:
			l = pos
		if val > 0 and pos > r:
			r = pos
		pos = word.find('B', pos + 1)
	if val > 0 and count < u:
		u = count
	if val > 0 and count > d:
		d = count
	b += val
	count += 1
if b == 0:
	print(1)
else:
	s = max(d - u + 1, r - l + 1)
	if s > n or s > m:
		print(-1)
	else:
		a = s ** 2
		print(a - b)


(bl, wt) = 'B W'.split()

def gd(f, l):
	return 2 * int(l > f) - 1

def fe(v, zf, zl, xf, xl, iv):
	dz = gd(zf, zl)
	dx = gd(xf, xl)
	for c in range(zf, zl, dz):
		for d in range(xf, xl, dx):
			t = v[c][d] if iv else v[d][c]
			if t == bl:
				return c

def cir(v, t, b, l, r):
	s = 0
	for c in range(t, b + 1):
		for d in range(l, r + 1):
			if v[c][d] == wt:
				s += 1
	return s

def pes(v, h, w, t, b, l, r):
	(lw, lh) = (r - l + 1, b - t + 1)
	ld = abs(lw - lh)
	if lw < lh:
		pd = l + w - r - 1
	elif lw > lh:
		pd = t + h - b - 1
	else:
		return 0
	if pd >= ld:
		return ld * max(lh, lw)
	return -1

def ge(v, h, w):
	t = fe(v, 0, h, 0, w, 1)
	b = fe(v, h - 1, -1, 0, w, 1)
	l = fe(v, 0, w, 0, h, 0)
	r = fe(v, w - 1, -1, 0, h, 0)
	return (t, b, l, r)

def wp(v, h, w):
	(t, b, l, r) = ge(v, h, w)
	if t == None:
		return 1
	si = cir(v, t, b, l, r)
	so = pes(v, h, w, t, b, l, r)
	if so < 0:
		return -1
	return si + so
(h, w) = [int(c) for c in input().split()]
v = []
for c in range(h):
	v.append(input())
print(wp(v, h, w))


read = lambda : map(int, input().split())
(n, m) = read()
a = [input() for i in range(n)]
cnt = sum((i.count('B') for i in a))
x1 = y1 = 1001
x2 = y2 = -1
for i in range(n):
	for j in range(m):
		if a[i][j] == 'B':
			x1 = min(x1, i)
			x2 = max(x2, i)
			y1 = min(y1, j)
			y2 = max(y2, j)
d = max(x2 - x1, y2 - y1) + 1
if cnt == 0:
	ans = 1
elif d > min(n, m):
	ans = -1
else:
	ans = d * d - cnt
print(ans)


(n, m) = [int(s) for s in input().split()]
g = [[0 for i in range(m)] for j in range(n)]
sum = 0
top = n - 1
bottom = 0
left = m - 1
right = 0
for i in range(n):
	f = str(input())
	for j in range(m):
		if f[j] == 'B':
			sum += 1
			top = min(top, i)
			bottom = max(bottom, i)
			left = min(left, j)
			right = max(right, j)
if sum == 0:
	print(1)
else:
	a = max(right - left + 1, bottom - top + 1)
	if a > n or a > m:
		print(-1)
	else:
		print(a ** 2 - sum)


(n, m) = map(int, input().split())
q = [str(input()) for i in range(n)]
k = 0
t = True
u = 0
li = vi = n * m
pi = ni = 0
for i in range(n):
	t = False
	u = 0
	for j in q[i]:
		if j == 'B':
			if u < li:
				li = u
			if u > pi:
				pi = u
			if i < vi:
				vi = i
			if i > ni:
				ni = i
			k += 1
		u += 1
if max(ni - vi, pi - li) + 1 > n or max(ni - vi, pi - li) + 1 > m:
	print(-1)
elif k == 0:
	print(1)
else:
	print((max(ni - vi, pi - li) + 1) ** 2 - k)


(n, m) = input().split(' ')
n = int(n)
m = int(m)
c = 0
(u_black, b_black, l_black, r_black) = (n, 0, m, 0)
for i in range(0, n):
	row = str(input())
	for j in range(0, m):
		if row[j] == 'B':
			u_black = min(u_black, i)
			b_black = max(b_black, i)
			l_black = min(l_black, j)
			r_black = max(r_black, j)
			c = c + 1
length = max(b_black - u_black + 1, r_black - l_black + 1)
if c == 0:
	print(1)
elif length > m or length > n:
	print(-1)
else:
	print(length * length - c)


def list_input():
	return list(map(int, input().split()))

def map_input():
	return map(int, input().split())

def map_string():
	return input().split()
(n, m) = map_input()
cnt = 0
upp = n + 1
low = -1
left = -1
right = m + 1
for i in range(n):
	a = list(input())
	cnt += a.count('B')
	for j in range(m):
		if a[j] == 'B':
			upp = min(upp, i)
			low = max(low, i)
			left = max(left, j)
			right = min(right, j)
x = abs(upp - low) + 1
y = abs(right - left) + 1
s = max(x, y)
if cnt == 0:
	print(1)
elif s > n or s > m:
	print(-1)
else:
	print(s * s - cnt)


(n, m) = (int(x) for x in input().split())
(i_left, j_left) = (n, m)
i_right = 0
j_right = 0
count = 0
for i in range(n):
	line = input()
	for j in range(m):
		if line[j] == 'B':
			count += 1
			if i < i_left:
				i_left = i
			if i > i_right:
				i_right = i
			if j < j_left:
				j_left = j
			if j > j_right:
				j_right = j
edge_len = max(i_right - i_left + 1, j_right - j_left + 1)
if count == 0:
	print(1)
elif edge_len > m or edge_len > n:
	print(-1)
else:
	print(edge_len * edge_len - count)


from sys import stdin, stdout

def rint():
	return map(int, stdin.readline().split())
(max_height, max_width) = rint()
c = [str()] * max_height
top = max_height
left = max_width
bottom = -1
right = -1
b_exist = 0
for i in range(max_height):
	c[i] = input()
	for j in range(max_width):
		if c[i][j] == 'B':
			b_exist = 1
			if top > i:
				top = i
			if left > j:
				left = j
			if bottom < i:
				bottom = i
			if right < j:
				right = j
if not b_exist:
	print(1)
	exit()
ans = 0
for i in range(top, bottom + 1):
	for j in range(left, right + 1):
		if c[i][j] == 'W':
			ans += 1
height = bottom - top + 1
width = right - left + 1
diff = abs(height - width)
if height > width:
	if diff + width > max_width:
		ans = -1
	else:
		ans += diff * height
elif height < width:
	if diff + height > max_height:
		ans = -1
	else:
		ans += diff * width
print(ans)


(n, m) = map(int, input().split())
g = [input() for i in range(n)]
(b, r1, r2, c1, c2) = (0, n, -1, m, -1)
for i in range(n):
	for j in range(m):
		if g[i][j] == 'B':
			b += 1
			r1 = min(r1, i)
			r2 = max(r2, i)
			c1 = min(c1, j)
			c2 = max(c2, j)
s = max(r2 - r1 + 1, c2 - c1 + 1)
if b == 0:
	print(1)
elif min(n, m) < s:
	print(-1)
else:
	print(s ** 2 - b)


def list_input():
	return list(map(int, input().split()))
[n, m] = list_input()
cell = list()
for i in range(n):
	cell.append(input())
ps = [[0 for j in range(m + 1)] for i in range(n + 1)]
for i in range(n):
	for j in range(m):
		a = 0
		if cell[i][j] == 'B':
			a = 1
		ps[i + 1][j + 1] = ps[i + 1][j] + ps[i][j + 1] - ps[i][j] + a
res = 1 << 30
for i in range(n):
	for j in range(m):
		h = n - i
		w = m - j
		lmax = min(h, w)
		for l in range(1, lmax + 1):
			cnt = ps[i + l][j + l] - ps[i][j + l] - ps[i + l][j] + ps[i][j]
			if cnt == ps[n][m]:
				res = min(res, l * l - ps[n][m])
if res == 1 << 30:
	print('-1')
else:
	print(res)


(n, m) = list(map(int, input().split()))
l = []
up = -1
down = -1
left = -1
right = -1
cout = 0
for i in range(n):
	s = input()
	for j in range(m):
		if s[j] == 'B':
			cout += 1
			if up == -1:
				up = i
				down = i
				left = j
				right = j
			else:
				down = i
				left = min(j, left)
				right = max(j, right)
side = max(down - up, right - left) + 1
if side == 0:
	side = 1
if side > n or side > m:
	print(-1)
else:
	print(side ** 2 - cout)


(n, m) = map(int, input().split())
b = 0
maxy = maxx = -1
miny = minx = max(m, n) - 1
for i in range(n):
	s = str(input())
	for j in range(m):
		if s[j] == 'B':
			b += 1
			minx = min(minx, j)
			maxx = max(maxx, j)
			miny = min(miny, i)
			maxy = max(maxy, i)
if b == 0:
	print(1)
else:
	dx = maxx - minx + 1
	dy = maxy - miny + 1
	d = max(dx, dy)
	if d > m or d > n:
		print(-1)
	else:
		t = d ** 2 - b
		print(t)


(n, m) = list(map(int, input().split()))
sheet = []
for i in range(n):
	sheet.append(input())
min_row = 101
max_row = -1
min_col = 101
max_col = -1
for i in range(n):
	for j in range(m):
		if sheet[i][j] == 'B':
			min_row = min(min_row, i)
			max_row = max(max_row, i)
			min_col = min(min_col, j)
			max_col = max(max_col, j)
l = max_row - min_row + 1
b = max_col - min_col + 1
if min_row == 101 and max_row == -1 and (min_col == 101) and (max_col == -1):
	print(1)
else:
	impossible = False
	if l < b:
		d = b - l
		if min_row - d >= 0:
			min_row = min_row - d
			d = 0
		else:
			d = d - (min_row - 0)
			min_row = 0
		if max_row + d < n:
			max_row = max_row + d
		else:
			impossible = True
	elif l > b:
		d = l - b
		if min_col - d >= 0:
			min_col = min_col - d
			d = 0
		else:
			d = d - (min_col - 0)
			min_col = 0
		if max_col + d < m:
			max_col = max_col + d
		else:
			impossible = True
	if not impossible:
		count = 0
		for row in range(min_row, max_row + 1):
			for col in range(min_col, max_col + 1):
				if sheet[row][col] == 'W':
					count += 1
		print(count)
	else:
		print('-1')


def polycarp(n, m, l):
	left = min(l).find('B')
	if left == -1:
		return 1
	right = m - min([x[::-1] for x in l]).find('B') - 1
	top = bottom = -1
	for i in range(n):
		if l[i].find('B') != -1:
			top = i
			break
	for i in range(n - 1, -1, -1):
		if l[i].find('B') != -1:
			bottom = i
			break
	w = right - left + 1
	h = bottom - top + 1
	if w > n or h > m:
		return -1
	r = 0
	for i in range(top, bottom + 1):
		for j in range(left, right + 1):
			if l[i][j] == 'W':
				r += 1
	if w > h:
		r += (w - h) * w
	else:
		r += (h - w) * h
	return r
(n, m) = list(map(int, input().strip().split()))
l = list()
for i in range(n):
	l.append(input().strip())
print(polycarp(n, m, l))


(n, m) = map(int, input().split())
l = []
for i in range(n):
	l.append(input())
r = []
c = []
total = 0
for i in range(n):
	for j in range(m):
		if l[i][j] == 'B':
			r.append(i)
			c.append(j)
			total += 1
if total != 0:
	mir = min(r)
	mar = max(r)
	x = mar - mir + 1
	mic = min(c)
	mac = max(c)
	y = mac - mic + 1
	h = max(x, y)
	if h > n or h > m:
		print(-1)
	else:
		print(h * h - total)
else:
	print(1)


from sys import exit

def getRowsContainingB(matrix):
	beginningRow = -1
	endingRow = -2
	for i in range(len(matrix)):
		for c in matrix[i]:
			if c == 'B':
				if beginningRow == -1:
					beginningRow = endingRow = i
				else:
					endingRow = i
	return endingRow - beginningRow + 1

def getColumnsContainingB(matrix):
	beginningColumn = -1
	endingColumn = -2
	for i in range(len(matrix[0])):
		for vector in matrix:
			if vector[i] == 'B':
				if beginningColumn == -1:
					beginningColumn = endingColumn = i
				else:
					endingColumn = i
	return endingColumn - beginningColumn + 1

def getNumberOfB(matrix):
	counter = 0
	for v in matrix:
		for c in v:
			if c == 'B':
				counter += 1
	return counter
(n, m) = map(int, input().split())
matrix = []
possible = True
for _ in range(n):
	vector = list(input())
	for c in vector:
		if c != 'W' and c != 'B':
			print(-1)
			exit()
	matrix.append(vector)
rows = getRowsContainingB(matrix)
columns = getColumnsContainingB(matrix)
sqrRoot = rows if rows > columns else columns
if sqrRoot == 0:
	print(1)
elif sqrRoot <= n and sqrRoot <= m:
	print(sqrRoot ** 2 - getNumberOfB(matrix))
else:
	print(-1)


(n, k) = map(int, input().split())
list1 = []
list2 = []
black = 0
side = 0
for i in range(n):
	line = input()
	for a in range(len(line)):
		if line[a] == 'B':
			list1.append(i)
			list2.append(a)
			black += 1
if black == 0:
	print(1)
else:
	side = max(max(list1) - min(list1) + 1, max(list2) - min(list2) + 1)
	if n < side or k < side:
		print(-1)
	else:
		print(side * side - black)


nandm = [int(i) for i in input().split()]
n = nandm[0]
m = nandm[1]
b = []
numB = 0
for i in range(n):
	string = list(input())
	for j in range(len(string)):
		if string[j] == 'B':
			b.append((j, n - i - 1))
			numB += 1
maxx = -1
maxy = -1
minx = m + 1
miny = n + 1
for x in b:
	if x[0] > maxx:
		maxx = x[0]
	if x[0] < minx:
		minx = x[0]
	if x[1] > maxy:
		maxy = x[1]
	if x[1] < miny:
		miny = x[1]
side = max(maxx - minx, maxy - miny) + 1
if numB == 0 or numB == 1:
	print(1 - numB)
elif side <= n and side <= m:
	print(side * side - numB)
else:
	print(-1)


(n, m) = map(int, input().split())
nn0 = n
nn1 = -1
mm0 = m
mm1 = -1
cnt = 0
for i in range(n):
	s = input().strip()
	if 'B' in s:
		nn0 = min(i, nn0)
		nn1 = max(i, nn1)
		mm0 = min(s.index('B'), mm0)
		mm1 = max(s.rindex('B'), mm1)
		cnt += sum(map(lambda z: z == 'B', s))
if nn1 < 0:
	print(1)
else:
	z = max(nn1 - nn0, mm1 - mm0) + 1
	if z <= min(m, n):
		print(z * z - cnt)
	else:
		print(-1)


(n, m) = map(int, input().split())
data = [input() for _ in range(n)]
rmax = cmax = -1
rmin = 1000
cmin = 1000
for i in range(n):
	for j in range(m):
		if data[i][j] == 'B':
			cmin = min(cmin, i)
			cmax = max(cmax, i)
			rmin = min(rmin, j)
			rmax = max(rmax, j)
row = rmax - rmin + 1
column = cmax - cmin + 1
side = max(row, column)
if rmax == -1 and cmax == -1:
	print(1)
elif side <= n and side <= m:
	w = 0
	for i in range(column):
		for j in range(row):
			if data[i + cmin][j + rmin] == 'W':
				w += 1
	if column > row:
		w += column * (column - row)
	elif row > column:
		w += row * (row - column)
	print(w)
else:
	print(-1)


(row, col) = map(int, input().split())
(lm, rm, tm, bm) = (101, -1, 101, -1)
count = 0
for i in range(row):
	current = input()
	for j in range(len(current)):
		if current[j] == 'B':
			count += 1
			if j < lm:
				lm = j
			if j > rm:
				rm = j
			if i < tm:
				tm = i
			if i > bm:
				bm = i
lengths = (rm - lm + 1, bm - tm + 1)
if lengths[0] < lengths[1]:
	if lengths[1] > col:
		print('-1')
	else:
		print(lengths[1] ** 2 - count)
elif lengths[1] < lengths[0]:
	if lengths[0] > row:
		print('-1')
	else:
		print(lengths[0] ** 2 - count)
elif count == 0:
	print(1)
else:
	print(lengths[0] ** 2 - count)


(n, m) = [int(x) for x in input().split()]
arr = []
(x1, x2, y1, y2) = (101, -1, 101, -1)
for i in range(n):
	arr.append(input().rstrip())
c1 = 0
for i in range(n):
	for j in range(m):
		if arr[i][j] == 'B':
			x1 = min(x1, j)
			x2 = max(x2, j)
			y1 = min(y1, i)
			y2 = max(y2, i)
			c1 = 1
count = 0
for j in range(x1, x2 + 1):
	for i in range(y1, y2 + 1):
		if arr[i][j] == 'W':
			count += 1
sizeX = x2 - x1 + 1
sizeY = y2 - y1 + 1
if not c1:
	print(1)
elif sizeX > sizeY:
	if sizeX > n:
		print(-1)
	else:
		print(count + sizeX * (sizeX - sizeY))
elif sizeY > sizeX:
	if sizeY > m:
		print(-1)
	else:
		print(count + sizeY * (sizeY - sizeX))
else:
	print(count)


(h, l) = [int(i) for i in input().split()]
a = []
for i in range(h):
	a.append(list(input()))
(left, right, down, up) = [l - 1, 0, 0, h - 1]
gg = True
for i in range(h):
	for j in range(l):
		if a[i][j] == 'B':
			gg = False
			if i < up:
				up = i
			if i > down:
				down = i
			if j > right:
				right = j
			if j < left:
				left = j
edge = max(down - up + 1, right - left + 1)
if edge > min(h, l):
	print(-1)
elif gg:
	print(1)
else:
	ans = 0
	for i in range(up, down + 1):
		for j in range(left, right + 1):
			if a[i][j] == 'W':
				ans += 1
	while left > 0 and right - left + 1 < edge:
		left -= 1
		ans += down - up + 1
	while right < l - 1 and right - left + 1 < edge:
		right += 1
		ans += down - up + 1
	while down < h - 1 and down - up + 1 < edge:
		down += 1
		ans += right - left + 1
	while up > 0 and down - up + 1 < edge:
		up -= 1
		ans += right - left + 1
	print(ans)


(n, m) = list(map(int, input().split()))
rows = []
cols = []
bl = 0
mat = []
for i in range(n):
	k = input()
	for j in range(m):
		if k[j] == 'B':
			rows.append(i)
			cols.append(j)
			bl += 1
J = False
if bl == 0:
	J = True
	print(1)
if not J:
	a = min(rows)
	b = max(rows)
	c = min(cols)
	d = max(cols)
	w = d - c + 1
	h = b - a + 1
	if w >= h:
		if w <= n:
			j = w * w - bl
		else:
			j = -1
	elif h > m:
		j = -1
	else:
		j = h * h - bl
	print(j)


tempArr = list(map(int, input().split()))
yLen = tempArr[0]
xLen = tempArr[1]
paperArr = []
blackXMin = [xLen, 0]
blackXMax = [0, 0]
blackYMin = [0, yLen]
blackYMax = [0, 0]
isNoBlacks = True
numBlacks = 0
for i in range(yLen):
	tempArr = list(input())
	for x in range(len(tempArr)):
		if tempArr[x] == 'B':
			numBlacks += 1
			isNoBlacks = False
			if x < blackXMin[0]:
				blackXMin = [x, i]
			if x > blackXMax[0]:
				blackXMax = [x, i]
			if i < blackYMin[1]:
				blackYMin = [x, i]
			if i > blackYMax[1]:
				blackYMax = [x, i]
	paperArr.append(tempArr)
xDiff = abs(blackXMax[0] - blackXMin[0]) + 1
yDiff = abs(blackYMax[1] - blackYMin[1]) + 1
if isNoBlacks == True:
	ans = str(1)
elif xDiff == yDiff and numBlacks == xDiff * yDiff:
	ans = str(0)
elif xDiff != yDiff and numBlacks == xLen * yLen:
	ans = str(-1)
elif yLen == 1 and xLen != 1:
	ans = str(-1)
elif xLen == 1 and yLen != 1:
	ans = str(-1)
elif xDiff > yDiff:
	if xDiff > yLen:
		ans = str(-1)
	else:
		ans = str(max(xDiff, yDiff) * max(xDiff, yDiff) - numBlacks)
elif yDiff > xLen:
	ans = str(-1)
else:
	ans = str(max(xDiff, yDiff) * max(xDiff, yDiff) - numBlacks)
print(ans)


nm = input().split(' ')
n = int(nm[0])
m = int(nm[1])
blich = []
for i in range(n):
	blich.append(list(input()))
nl = [0, 0]
nr = [0, 0]
sl = [0, 0]
sr = [0, 0]
dflt = (-1, -1)
num = 0
for i in range(n):
	for j in range(m):
		if blich[i][j] == 'B':
			if num > 0:
				num += 1
			elif num == 0:
				num += 1
				nl = [i, j]
				nr = [i, j]
				sl = [i, j]
				sr = [i, j]
for i in range(n):
	for j in range(m):
		if blich[i][j] == 'B':
			if i < nl[0]:
				nl[0] = i
			if j < nl[1]:
				nl[1] = j
			if i < sl[0]:
				sl[0] = i
			if j > sl[1]:
				sl[1] = j
			if i > nr[0]:
				nr[0] = i
			if j < nr[1]:
				nr[1] = j
			if i > sr[0]:
				sr[0] = i
			if j > sr[1]:
				sr[1] = j
lastfm1 = [max(nr[0], nl[0], sr[0], sl[0]), max(nr[1], nl[1], sr[1], sl[1])]
lastfm2 = [min(nr[0], nl[0], sr[0], sl[0]), min(nr[1], nl[1], sr[1], sl[1])]
fm1 = lastfm1[0] - lastfm2[0] + 1
fm2 = lastfm1[1] - lastfm2[1] + 1
fm = max(fm1, fm2)
if fm > n or fm > m:
	print(-1)
else:
	print(fm * fm - num)


(r, s) = map(int, input().split())
p = [[] for i in range(r)]
q = [[0 for j in range(s)] for i in range(r)]
for i in range(r):
	for (j, c) in enumerate(input()):
		p[i].append(c == 'B')
		q[i][j] = q[i][j - 1] * bool(j) + q[i - 1][j] * bool(i) - q[i - 1][j - 1] * bool(i and j) + (not p[i][j])
blacks = r * s - q[-1][-1]
mini = 10 ** 10
for i2 in range(r):
	for j2 in range(s):
		for k in range(min(i2, j2) + 1):
			i1 = i2 - k
			j1 = j2 - k
			x = q[i2][j2] + q[i1 - 1][j1 - 1] * bool(i1 and j1) - q[i1 - 1][j2] * bool(i1) - q[i2][j1 - 1] * bool(j1)
			if blacks + x == (i2 - i1 + 1) * (j2 - j1 + 1):
				mini = min(mini, x)
if mini == 10 ** 10:
	print(-1)
else:
	print(mini)


(n, m) = (int(i) for i in input().split())
top = -1
left = 101
right = -1
down = -1
cnt = 0
for i in range(n):
	read = input()
	for j in range(m):
		cur = read[j] == 'B'
		if not cur:
			continue
		cnt += 1
		if top == -1:
			top = i
		if j < left:
			left = j
		if j > right:
			right = j
		down = i
stor = max(down - top, right - left) + 1
if n < stor or m < stor:
	print(-1)
else:
	print(stor ** 2 - cnt)


import sys
(n, m) = [*map(int, input().split())]
s = ['' for i in range(0, n)]
for i in range(0, n):
	s[i] = input()
cnt = [[0 for x in range(0, m)] for i in range(0, n)]
cnt2 = [[0 for x in range(0, m)] for i in range(0, n)]
maxI = -1
maxJ = -1
minI = n
minJ = m
for i in range(0, n):
	for j in range(0, m):
		if j > 0:
			cnt[i][j] += cnt[i][j - 1]
		if i > 0:
			cnt[i][j] += cnt[i - 1][j]
		if i > 0 and j > 0:
			cnt[i][j] -= cnt[i - 1][j - 1]
		if s[i][j] is 'B':
			cnt[i][j] += 1
		if cnt[i][j] >= 1:
			minI = min(minI, i)
			minJ = min(minJ, j)
for i in range(n - 1, -1, -1):
	for j in range(m - 1, -1, -1):
		if j + 1 < m:
			cnt2[i][j] += cnt2[i][j + 1]
		if i + 1 < n:
			cnt2[i][j] += cnt2[i + 1][j]
		if i + 1 < n and j + 1 < m:
			cnt2[i][j] -= cnt2[i + 1][j + 1]
		if s[i][j] is 'B':
			cnt2[i][j] += 1
		if cnt2[i][j] >= 1:
			maxI = max(maxI, i)
			maxJ = max(maxJ, j)
res = -1
if minI == n:
	print(1)
	sys.exit(0)
rowDif = maxI - minI
colDif = maxJ - minJ
if rowDif >= m or colDif >= n:
	print(-1)
	sys.exit(0)
diff = abs(rowDif - colDif)
if rowDif > colDif:
	mini = min(m - 1 - maxJ, diff)
	diff -= mini
	minJ -= diff
	maxJ += mini
else:
	mini = min(n - 1 - maxI, diff)
	diff -= mini
	minI -= diff
	maxI += mini
totalBlack = cnt[maxI][maxJ]
if minI > 0:
	totalBlack -= cnt[minI - 1][maxJ]
if minJ > 0:
	totalBlack -= cnt[maxI][minJ - 1]
if minI > 0 and minJ > 0:
	totalBlack += cnt[minI - 1][minJ - 1]
rowDif = max(rowDif, colDif)
res = (rowDif + 1) * (rowDif + 1) - totalBlack
print(res)


(n, m) = [int(x) for x in input().split()]
sheet = []
for i in range(n):
	sheet.append(input())
numB = 0
for i in range(n):
	numB += sheet[i].count('B')
topRow = -1
bottomRow = -1
leftCol = -1
rightCol = -1
for i in range(n):
	if 'B' in sheet[i]:
		topRow = i
		break
for i in range(n - 1, -1, -1):
	if 'B' in sheet[i]:
		bottomRow = i
		break
for j in range(m):
	if leftCol > -1:
		break
	for i in range(n):
		if sheet[i][j] == 'B':
			leftCol = j
for j in range(m - 1, -1, -1):
	if rightCol > -1:
		break
	for i in range(n):
		if sheet[i][j] == 'B':
			rightCol = j
height = bottomRow - topRow + 1
length = rightCol - leftCol + 1
side = height if height > length else length
if side > m or side > n:
	print(-1)
else:
	print(side ** 2 - numB)


r = 0
d = 0
s = 0
(n, m) = map(int, input().split())
l = m - 1
u = n - 1
for i in range(n):
	line = input()
	for (j, c) in enumerate(line):
		if c == 'B':
			s = s + 1
			l = min(l, j)
			r = max(r, j)
			d = max(d, i)
			u = min(u, i)
a = max(r - l + 1, d - u + 1, 1)
if a < 0 or a > n or a > m:
	print(-1)
else:
	print(a * a - s)


import sys
(n, m) = map(int, input().split())
arr = sys.stdin.readlines()
cnt = gotW = 0
rmin = cmin = 101
rmax = cmax = -1
for i in range(n):
	for j in range(m):
		if arr[i][j] == 'B':
			cnt += 1
			if rmin > i:
				rmin = i
			if rmax < i:
				rmax = i
			if cmin > j:
				cmin = j
			if cmax < j:
				cmax = j
m2 = max(rmax - rmin + 1, cmax - cmin + 1)
if m2 > n or m2 > m:
	print('-1')
elif cnt == 0:
	print(1)
else:
	print(m2 * m2 - cnt)


(n, m) = map(int, input().split())
(minx, maxx, miny, maxy, total) = (101, 0, 101, 0, 0)
for i in range(n):
	string = input()
	for j in range(m):
		if string[j] == 'B':
			total += 1
			minx = min(minx, j)
			maxx = max(maxx, j)
			miny = min(miny, i)
			maxy = max(maxy, i)
ans = max(maxx - minx + 1, maxy - miny + 1)
if ans > min(m, n):
	print(-1)
elif total == 0:
	print(1)
else:
	print(ans ** 2 - total)


(n, m) = map(int, input().split())
our = [input() for i in range(n)]
first = -1
for i in range(n):
	if 'B' in our[i]:
		first = i
		break
last = -1
for i in range(n - 1, -1, -1):
	if 'B' in our[i]:
		last = i
		break
if first == -1:
	print(1)
else:
	f2 = -1
	l2 = -1
	for i in range(m):
		a = [our[j][i] for j in range(n)]
		if 'B' in a:
			f2 = i
			break
	for i in range(m - 1, -1, -1):
		a = [our[j][i] for j in range(n)]
		if 'B' in a:
			l2 = i
			break
	if last - first + 1 > m or l2 - f2 + 1 > n:
		print(-1)
	else:
		res = 0
		for i in range(first, last + 1):
			for j in range(f2, l2 + 1):
				if our[i][j] == 'W':
					res += 1
		res += max(last - first + 1, l2 - f2 + 1) ** 2 - (last - first + 1) * (l2 - f2 + 1)
		print(res)


(n, m) = map(int, input().split())
min_x = m
min_y = n
max_x = 0
max_y = 0
r = -1
s = 0
for y in range(n):
	str = input()
	for x in range(m):
		if str[x] == 'B':
			s += 1
			if y < min_y:
				min_y = y
			if x < min_x:
				min_x = x
			if y > max_y:
				max_y = y
			if x > max_x:
				max_x = x
if s > 0:
	w = max_x - min_x + 1
	h = max_y - min_y + 1
	offset = abs(w - h)
	if w < h:
		if offset + w <= m:
			w += offset
	elif h < w and offset + h <= n:
		h += offset
	if w == h:
		r = w * h - s
else:
	r = 1
print(r)


(n, m) = map(int, input().split())
a = []
b = []
maxU = n
maxD = -1
maxL = m
maxR = -1
let = 0
for i in range(n):
	ent = input()
	for j in range(m):
		b.append(ent[j])
	a.append(b)
	b = []
for i in range(n):
	for j in range(m):
		if a[i][j] == 'B':
			let += 1
			if i < maxU:
				maxU = i
			if i > maxD:
				maxD = i
			if j < maxL:
				maxL = j
			if j > maxR:
				maxR = j
st = 0
res = 0
if maxD - maxU + 1 > maxR - maxL + 1:
	st = maxD - maxU + 1
else:
	st = maxR - maxL + 1
if let == 0:
	print('1')
elif st <= n and st <= m:
	res = st * st - let
	print(res)
else:
	print('-1')


(n, m) = list(map(int, input().split()))
arr = [0] * (n + 1)
for i in range(n):
	arr[i] = input()
cntb = 0
mn = 200
mx = 0
for i in range(n):
	first = True
	for j in range(m):
		if arr[i][j] == 'B':
			cntb += 1
			if first:
				mn = min(mn, j)
				mx = max(mx, j)
				first = False
			else:
				mx = max(mx, j)
mn2 = 200
mx2 = 0
if cntb == 0:
	print(1)
	return
elif cntb == 1:
	print(0)
	return
for i in range(m):
	first = True
	for j in range(n):
		if arr[j][i] == 'B':
			if first:
				mn2 = min(mn2, j)
				mx2 = max(mx2, j)
				first = False
			else:
				mx2 = max(mx2, j)
val = max(mx - mn + 1, mx2 - mn2 + 1)
if val > m or val > n:
	print(-1)
	return
print(val * val - cntb)


def solve():
	(n, m) = get([int])
	grid = [get(str) for _ in range(n)]
	try:
		left = min((j for i in range(n) for j in range(m) if grid[i][j] == 'B'))
	except Exception:
		return 1
	right = max((j for i in range(n) for j in range(m) if grid[i][j] == 'B'))
	top = min((i for i in range(n) for j in range(m) if grid[i][j] == 'B'))
	bott = max((i for i in range(n) for j in range(m) if grid[i][j] == 'B'))
	w = right - left + 1
	h = bott - top + 1
	if max(w, h) > min(n, m):
		return -1
	count = sum((1 for i in range(top, bott + 1) for j in range(left, right + 1) if grid[i][j] == 'W'))
	return count + max(w, h) ** 2 - w * h
_testcases = '\n5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW\n\n5\n\n1 2\nBB\n\n-1\n\n3 3\nWWW\nWWW\nWWW\n\n1\n\n5 4\nBWBW\nWWWW\nWWWW\nWWWW\nWWBW\n\n-1\n\n5 4\nBWWB\nWWWW\nWWWW\nWWWB\nWWWW\n\n13\n\n5 4\nWBBW\nWBBW\nWWWW\nWWWW\nWWWW\n\n0\n'.strip()
import re
import sys
import math
import heapq
from heapq import heapify, heappop, heappush
import bisect
from bisect import bisect_left, bisect_right
import operator
from operator import itemgetter, attrgetter
import itertools
import collections
inf = float('inf')
sys.setrecursionlimit(10000)

def tree():
	return collections.defaultdict(tree)

def cache(func):
	cache_dict = {}

	def _cached_func(*args, _get_cache=False):
		if _get_cache:
			return cache_dict
		if args in cache_dict:
			return cache_dict[args]
		cache_dict[args] = func(*args)
		return cache_dict[args]
	return _cached_func

def equal(x, y, epsilon=1e-06):
	if -epsilon <= x - y <= epsilon:
		return True
	if -epsilon <= x <= epsilon or -epsilon <= y <= epsilon:
		return False
	return -epsilon <= (x - y) / x <= epsilon or -epsilon <= (x - y) / y <= epsilon

def get(_type):
	if type(_type) == list:
		if len(_type) == 1:
			_type = _type[0]
			return list(map(_type, input().strip().split()))
		else:
			return [_type[i](inp) for (i, inp) in enumerate(input().strip().split())]
	else:
		return _type(input().strip())
print(solve())


import sys
from math import *

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())
(n, m) = mints()
(mx, my, MX, MY) = (10 ** 9, 10 ** 9, -10 ** 9, -10 ** 9)
a = [None] * n
for i in range(n):
	s = list(minp())
	a[i] = s
	for j in range(len(s)):
		if s[j] == 'B':
			mx = min(mx, j)
			my = min(my, i)
			MX = max(MX, j)
			MY = max(MY, i)
if mx == 10 ** 9:
	print(1)
else:
	while MX - mx != MY - my:
		if MX - mx < MY - my:
			if mx > 0:
				mx -= 1
			elif MX < m - 1:
				MX += 1
			else:
				break
		elif my > 0:
			my -= 1
		elif MY < n - 1:
			MY += 1
		else:
			break
	if MX - mx != MY - my:
		print(-1)
	else:
		r = 0
		for i in range(my, MY + 1):
			for j in range(mx, MX + 1):
				if a[i][j] != 'B':
					r += 1
		print(r)


(n, m) = map(int, input().split())
field = [input() for _ in range(n)]
black = 0
minheight = minwidth = 101
maxheight = maxwidth = 0
for i in range(n):
	s = field[i]
	for j in range(m):
		if s[j] == 'B':
			black += 1
			minheight = min(i, minheight)
			maxheight = max(i, maxheight)
			minwidth = min(j, minwidth)
			maxwidth = max(j, maxwidth)
if black == 0:
	print(1)
else:
	a = maxwidth - minwidth + 1
	b = maxheight - minheight + 1
	c = max(a, b)
	des = c * c
	if des > n * m or c > n or c > m:
		print(-1)
	else:
		print(des - black)


from sys import stdin, stdout
(n, m) = map(int, stdin.readline().split())
maps = []
challengers = []
for i in range(n):
	maps.append(stdin.readline().strip())
mins = [float('inf'), float('inf')]
maxs = [float('-inf'), float('-inf')]
for i in range(n):
	for j in range(m):
		if maps[i][j] == 'B':
			if i < mins[0]:
				mins[0] = i
			if j < mins[1]:
				mins[1] = j
			if i > maxs[0]:
				maxs[0] = i
			if j > maxs[1]:
				maxs[1] = j
if mins != [float('inf'), float('inf')] and max(abs(maxs[1] - mins[1]), abs(maxs[0] - mins[0])) >= min(n, m):
	stdout.write('-1')
elif mins == [float('inf'), float('inf')]:
	stdout.write('1')
else:
	ans = 0
	for i in range(mins[0], maxs[0] + 1):
		for j in range(mins[1], maxs[1] + 1):
			if maps[i][j] != 'B':
				ans += 1
	if abs(maxs[1] - mins[1]) > abs(maxs[0] - mins[0]):
		ans += (abs(maxs[1] - mins[1]) - abs(maxs[0] - mins[0])) * abs(maxs[1] - mins[1] + 1)
	elif abs(maxs[1] - mins[1]) < abs(maxs[0] - mins[0]):
		ans += (abs(maxs[0] - mins[0]) - abs(maxs[1] - mins[1])) * abs(maxs[0] - mins[0] + 1)
	stdout.write(str(ans))


(n, m) = map(int, input().split())
a = [input() for i in range(n)]
x1 = y1 = 10 ** 10
x2 = y2 = -1
cnt = 0
for i in range(n):
	for j in range(m):
		if a[i][j] == 'B':
			x1 = min(x1, i)
			x2 = max(x2, i)
			y1 = min(y1, j)
			y2 = max(y2, j)
			cnt += 1
dx = x2 - x1 + 1
dy = y2 - y1 + 1
if cnt == 0:
	ans = 1
elif max(dx, dy) <= min(n, m):
	ans = max(dx, dy) ** 2 - cnt
else:
	ans = -1
print(ans)


while True:
	try:
		(n, m) = map(int, input().split())
		a = []
		x1 = y1 = 11111111
		x2 = y2 = z = 0
		for i in range(0, n):
			x = list(input())
			a.append(x)
		for i in range(0, n):
			for j in range(0, m):
				if a[i][j] == 'B':
					z += 1
					x1 = min(x1, i)
					x2 = max(x2, i)
					y1 = min(y1, j)
					y2 = max(y2, j)
		if z == 0:
			print(1)
			continue
		ans = max(x2 - x1, y2 - y1) + 1
		if ans > n or ans > m:
			print(-1)
		else:
			print(ans * ans - z)
	except EOFError:
		break


from __future__ import division, print_function
from io import BytesIO, IOBase
import os, sys, math, heapq, copy
from collections import defaultdict, deque
from bisect import bisect_left, bisect_right
from functools import cmp_to_key
from itertools import permutations, combinations, combinations_with_replacement
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 1000000007

def get_int():
	return int(sys.stdin.readline().strip())

def get_str():
	return sys.stdin.readline().strip()

def get_float():
	return float(sys.stdin.readline().strip())

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_strs():
	return map(str, sys.stdin.readline().strip().split())

def get_floats():
	return map(float, sys.stdin.readline().strip().split())

def list_ints():
	return list(map(int, sys.stdin.readline().strip().split()))

def list_strs():
	return list(map(str, sys.stdin.readline().strip().split()))

def list_floats():
	return list(map(float, sys.stdin.readline().strip().split()))
(n, m) = get_ints()
blacks = 0
sr = sc = math.inf
er = ec = -math.inf
for i in range(n):
	s = get_str()
	for j in range(m):
		if s[j] == 'B':
			sr = min(sr, i)
			sc = min(sc, j)
			er = max(sr, i)
			ec = max(ec, j)
			blacks += 1
if sr == math.inf:
	sr = sc = er = ec = 0
length = max(er - sr, ec - sc) + 1
if length > n or length > m:
	print(-1)
else:
	print(pow(length, 2) - blacks)


(n, m) = map(int, input().split())
cells = [input() for _ in range(n)]
bcells = [i for i in range(n) if 'B' in cells[i]]
if not bcells:
	print(1)
else:
	(up, down) = (bcells[0], bcells[-1])
	left = min((cells[i].find('B') for i in bcells))
	right = max((cells[i].rfind('B') for i in bcells))
	(ver, hor) = (down - up + 1, right - left + 1)
	if ver > m or hor > n:
		print(-1)
	else:
		cnt = sum([cells[i][left:right + 1].count('W') for i in range(up, down + 1)])
		if ver > hor:
			cnt += (ver - hor) * ver
		elif hor > ver:
			cnt += (hor - ver) * hor
		print(cnt)


import sys
import math
inp = input()
sqr = []
for line in sys.stdin:
	s = list(line.rstrip())
	sqr.append(s)
r = -1
l = math.inf
d = -1
u = math.inf
for (i, line) in enumerate(sqr):
	for (j, b) in enumerate(line):
		if b == 'B':
			if i < u:
				u = i
			if i + 1 > d:
				d = i + 1
			if j < l:
				l = j
			if j + 1 > r:
				r = j + 1
ans = -1
if r != -1:
	ver = d - u
	hor = r - l
	if ver < hor:
		while ver < hor:
			if u > 0:
				u -= 1
				ver += 1
			elif d < len(sqr):
				d += 1
				ver += 1
			else:
				break
		else:
			ans = 0
	elif ver > hor:
		while ver > hor:
			if l > 0:
				l -= 1
				hor += 1
			elif r < len(sqr[0]):
				r += 1
				hor += 1
			else:
				break
		else:
			ans = 0
	else:
		ans = 0
else:
	ans = 1
if ans == 0:
	for i in range(u, d):
		for j in range(l, r):
			if sqr[i][j] == 'W':
				ans += 1
print(ans)


(n, m) = list(map(int, input().split()))
sheet = []
for i in range(n):
	sheet.append(input())
min_row = 101
max_row = -1
min_col = 101
max_col = -1
count_black = 0
for i in range(n):
	for j in range(m):
		if sheet[i][j] == 'B':
			count_black += 1
			min_row = min(min_row, i)
			max_row = max(max_row, i)
			min_col = min(min_col, j)
			max_col = max(max_col, j)
l = max(max_row - min_row + 1, max_col - min_col + 1)
if count_black == 0:
	print(1)
elif l > n or l > m:
	print(-1)
else:
	print(l * l - count_black)


(n, m) = list(map(int, input().split()))
minI = maxI = minJ = maxJ = -1
sumOfB = 0
for x in range(n):
	s = input()
	for el in range(len(s)):
		if s[el] == 'B':
			sumOfB += 1
			if minI == -1:
				minI = maxI = el
				minJ = maxJ = x
				continue
			if minI > el:
				minI = el
			if maxI < el:
				maxI = el
			if minJ > x:
				minJ = x
			if maxJ < x:
				maxJ = x
if max(maxI - minI + 1, maxJ - minJ + 1) > min(n, m):
	print(-1)
else:
	print(max(maxI - minI + 1, maxJ - minJ + 1) ** 2 - sumOfB)


from math import sqrt
(n, m) = map(int, input().split())
a = []
b = []
c = []
e = []
counter = 0
for i in range(n):
	s = input()
	for j in range(m):
		if s[j] == 'B':
			counter += 1
			c.append(j + 1)
			e.append(i + 1)
		b.append(s[j])
	a.append(b)
	b = []
if len(c) == 0:
	print(1)
else:
	s = max(max(c) - min(c) + 1, max(e) - min(e) + 1)
	if s <= n and s <= m:
		print(s * s - counter)
	else:
		print(-1)


(n, m) = map(int, input().split())
(x1, y1, x2, y2, c) = (m, n, 0, 0, 0)
for i in range(n):
	s = input()
	for j in range(m):
		if s[j] == 'B':
			if x1 > j:
				x1 = j
			if x2 < j:
				x2 = j
			if y1 > i:
				y1 = i
			if y2 < i:
				y2 = i
			c += 1
if c == 0:
	print(1)
else:
	w = x2 - x1 + 1
	h = y2 - y1 + 1
	h = max(w, h)
	if h > n or h > m:
		print(-1)
	else:
		print(h * h - c)


(n, m) = map(int, input().split())
sheet = []
for r in range(n):
	ir = list(input().strip())
	sheet.append(ir)
(minx, miny, maxx, maxy) = (101, 101, -1, -1)
seen = False
for r in range(n):
	for c in range(m):
		if sheet[r][c] == 'B':
			if minx > c:
				minx = c
			if maxx < c:
				maxx = c
			if miny > r:
				miny = r
			if maxy < r:
				maxy = r
			seen = True
length = max(maxy - miny + 1, maxx - minx + 1)
if seen == False:
	print(1)
elif length > m or length > n:
	print(-1)
else:
	counter = 0
	for i in range(miny, maxy + 1):
		for l in range(minx, maxx + 1):
			if sheet[i][l] == 'B':
				counter += 1
	print(length * length - counter)


(n, m) = map(int, input().split())
arr = []
max_x = []
max_y = []
for i in range(n):
	arr.append(input())
for i in range(n):
	for j in range(m):
		if arr[i][j] == 'B':
			max_x.append(j)
			max_y.append(i)
if len(max_x) == 0:
	print(1)
	exit()
dif_x = max(max_x) - min(max_x) + 1
dif_y = max(max_y) - min(max_y) + 1
size = max(dif_x, dif_y)
if size > n or size > m:
	print(-1)
	exit()
else:
	print(size ** 2 - len(max_x))


(rows, cols) = [int(i) for i in input().strip().split()]
b_present = False
(l, r, u, d) = (cols, cols, rows, -1)
b_cnt = 0
for i in range(rows):
	col = input().strip()
	if 'B' in col:
		b_present = True
		l = min(l, col.index('B'))
		u = min(u, i)
		r = min(r, col[::-1].index('B'))
		d = max(d, i)
		b_cnt += col.count('B')
if not b_present:
	print(1)
else:
	r = cols - r - 1
	if r - l + 1 > rows or d - u + 1 > cols:
		print(-1)
	else:
		print(max(r - l + 1, d - u + 1) * max(r - l + 1, d - u + 1) - b_cnt)