We need to parse the problem: We have an n x m grid initially with some black cells. We can paint additional white cells black to achieve a configuration where all black cells form exactly a square (with sides parallel to axes). The square must be of positive integer side length L >= 1. After painting, all cells inside the square (including possibly originally white) become black; all cells outside the square must be white. So we need to choose a square (defined by its top-left corner (r, c) and side length L) such that:
- For all cells inside the square (i from r to r+L-1, j from c to c+L-1): they must be black after painting (so any white cells inside must be painted black; we count them).
- For all cells outside the square: they must be white after painting (so any originally black cells outside must be painted white, but we are only allowed to paint white cells black? Actually the operation says: "paint minimum possible number of white cells with black so that all black cells form a square." It says we can paint white cells black. It does not say we can paint black cells white. So we are not allowed to change black to white; we can only add black paint. Therefore the final configuration must have black cells exactly those of some square, but we cannot erase existing black cells. So any existing black cell that lies outside the square would remain black, violating the condition that all cells outside the square are white. Hence it is impossible if there is any black cell outside the chosen square. Similarly, any white cell inside the square must be painted black, costing us. So we need to choose a square that contains all existing black cells, and contains no black cells outside (i.e., all existing black cells must be within the square, and the square must not contain any white cells? Actually it can contain white cells that we will paint black, that's fine). But also the square must be exactly the set of black cells: meaning after painting, all cells inside are black, all outside are white. Since we cannot turn black to white, we require that initially there are no black cells outside the square. And for cells inside the square, if some are white, we paint them black, cost = number of white cells inside.
Additionally, note: The square's side should have positive length. So at least 1.
Thus the problem reduces to: Find a square (with integer coordinates, sides parallel to axes, completely within the n x m grid) such that:
-
All existing black cells lie within the square (i.e., square must cover the bounding box of all black cells? Not exactly; but the square must contain all black cells, but can also contain white cells. So condition: For each black cell (i,j), we must have r ≤ i ≤ r+L-1 and c ≤ j ≤ c+L-1.
-
There is no black cell outside the square; that condition is automatically ensured if we ensure all black cells are inside. But careful: The square must also not extend beyond grid? Actually the square is placed on the sheet; it must be fully contained within the n x m? The problem statement: "all black cells form a square." It doesn't explicitly say the square must be within the sheet? But it must be, because black cells are on the sheet. The square's cells are the black cells, so they must be within the sheet. So the square coordinates must satisfy 1 ≤ r ≤ r+L-1 ≤ n, 1 ≤ c ≤ c+L-1 ≤ m. So square must be fully inside grid.
-
Additionally, we need that after painting, all cells outside the square are white. Since we cannot change black to white, we need that initially, there are no black cells outside the square. So that condition is just that all black cells are inside the square.
Thus the only condition is: All black cells are exactly a subset of the square, and no black cells outside. So square must contain all black cells. There is no additional condition like square must be exactly the set of black cells after painting? Actually the wording: "paint minimum possible number of white cells with black so that all black cells form a square. ... All the cells that do not belong to the square should be white." So final condition: The set of black cells equals exactly the set of cells in some square. That means: (1) All cells in the square are black; (2) No cell outside the square is black. Since we can only add black paint, we must have that initially all cells outside the square are white (otherwise they would remain black). So condition (2) requires that there are zero black cells outside the square initially. Condition (1) requires that all cells inside the square become black; we can paint white cells inside black, but if there are any black cells inside, they stay black. So that's fine. So the constraints are:
- Initially, black cells must be a subset of the square.
- Square must contain all black cells.
- Square must be fully inside grid.
Goal: minimize the number of white cells inside the square that need to be painted black, i.e., number of cells inside square that are initially white.
That's it.
But note: Could there be a case where the minimal square that contains all black cells is not necessarily the optimal because a larger square might cost more white cells? Actually we want to minimize the number of white cells we paint, i.e., minimize (area of square - number of existing black cells inside square). Because all cells inside need to become black; the existing black cells are already black, so we need to paint the white ones. So cost = area(L) - (number of black cells inside square). Since all black cells are inside, number of black cells inside = total number of black cells (because all black cells are inside the square, and there are none outside). So cost = L^2 - B, where B = total number of black cells initially? Wait, careful: Is it guaranteed that all black cells are inside the square? Yes, we require that. So the number of black cells inside the square equals B (since no black outside). But what if there are black cells inside the square that we counted? Yes, they are part of B. So the total number of black cells initially is B. So cost = L^2 - B. However, is it possible that some black cells are inside the square but we count them? Yes. So cost is L^2 - B, where L is side length of square. But we must also ensure that the square contains all black cells; but if the square is larger than necessary, L^2 - B increases, so it's not beneficial. So the minimal cost would be achieved by the smallest square that can contain all black cells. However, there is a twist: The square must be placed somewhere; it's not necessarily the minimal axis-aligned bounding square of the black cells? Could be larger, but larger L increases cost. So we want smallest L such that there exists a square of side L inside the grid that covers all black cells. However, the smallest L that can cover all black cells is determined by the dimensions of the bounding box: Let min_i, max_i be the min and max row indices of black cells; similarly min_j, max_j for columns. To cover all black cells, the square must have side length at least max( max_i - min_i + 1, max_j - min_j + 1 ) = D. Because we need to cover the spread in both directions. But also the square can be placed anywhere, so we can shift the square to encompass these cells as long as it fits within grid. So the minimal possible L is at least D. But maybe D is not achievable because the square of side D must be placed such that it covers all cells. For a given D, we need to check if there exists a square of side D that contains all black cells. Since the square is axis-aligned, containing all black cells means: There exist r and c such that:
r ≤ min_i, r + D - 1 ≥ max_i,
c ≤ min_j, c + D - 1 ≥ max_j.
Thus r ≤ min_i and r ≥ max_i - D + 1, similarly for c. So r must be in [max(1, max_i - D + 1) , min(min_i, n - D + 1)]? Actually also the square must be fully inside grid: 1 ≤ r ≤ n - D + 1, 1 ≤ c ≤ m - D + 1. So the feasible r interval is:
r_low = max(1, max_i - D + 1) // to have r + D - 1 ≥ max_i => r ≥ max_i - D + 1.
r_high = min(min_i, n - D + 1) // to have r ≤ min_i and also r ≤ n-D+1 for within grid.
Similarly for c. Feasibility requires r_low ≤ r_high and c_low ≤ c_high.
If such r,c exist, then D is achievable. Then cost = D^2 - B.
But is it necessarily minimal? Could a square with larger L yield lower cost? No, because cost = L^2 - B, which increases with L (since L^2 is increasing for L≥1, B is constant). So we want minimal L.
However, there is a nuance: B is constant, but L^2 - B might be negative if B > L^2? That can't happen because if all black cells are inside a square of area L^2, then B ≤ L^2. So it's non-negative. So minimizing L gives minimal cost.
But wait: The square must have sides parallel to painting's sides. That's already axis-aligned.
Thus the solution appears simple: Compute all black cells positions. Let B = count. If B == 0, then we can choose any 1x1 square; cost = 1 - 0 = 1 (as per example 3). So answer 1.
If B > 0, compute min_row, max_row, min_col, max_col. Let required_side = max(max_row - min_row + 1, max_col - min_col + 1). Then we need to check if a square of side required_side can be placed within the grid covering all black cells. The placement must satisfy constraints above: There exists r and c such that the square fits and covers the black cells. Since required_side is minimal possible to cover the spread, we need to check if we can shift it to fit within the grid. If yes, answer = required_side^2 - B. If not, try larger side lengths? Because if the minimal side doesn't fit, perhaps a larger side can fit? Example: grid is 1x2, black cells at (1,1) and (1,2). Then min_row=1, max_row=1, min_col=1, max_col=2. required_side = max(1,2) = 2. But grid is 1x2, which can't accommodate a 2x2 square (since n=1, m=2). So check: For D=2, we need to place a 2x2 square fully within the grid. But n=1 <2, so impossible. So we need to try larger D? Actually a larger side will also be at least 2, but if D=2 is impossible due to dimensions, any D>=2 will also be impossible because n=1 < D. So answer -1. That matches example 2.
But consider a case where n=2, m=3, black cells at (2,1) and (2,3). Then min_row=2, max_row=2 (so row span=1), min_col=1, max_col=3 (col span=3). required_side = 3. But n=2, cannot have side 3 because n<3. So required_side=3 not possible. But could we use side=3? Not possible. But could we use side=2? That would not cover column span of 3 because columns 1 to 3 need coverage; a side 2 square can cover at most width 2, cannot cover both columns 1 and 3 simultaneously. So no square can cover them because col spread is 3, so side must be at least 3. Since side>=3 and n<3, impossible. So -1.
Now consider a case where the spread fits within the grid but the minimal square's required placement might go out of bounds because the minimal r or c needed to cover the black cells might be forced to be less than 1 or > n-D+1. For example, black cells at row indices 1 and 5 in a 5x5 grid: min_row=1, max_row=5, row_span=5, required_side=5. For D=5, we need to place square of size 5. The only possible placement is r=1 to 5, c similarly. But is it possible? Since n=5, D=5 fits exactly. So ok. If min_row=2, max_row=5, span=4, D=4? But maybe min_col and max_col require D=4, but the grid is 5x5. Check: r must satisfy r ≤ min_row=2 and r ≥ max_row-D+1 =5-4+1=2, so r=2. That's valid if 2 ≤ n-D+1=5-4+1=2, so yes. So minimal D fits.
But what if black cells are near the edge such that the required square to cover them would extend beyond grid if we use minimal D? For instance, n=3, m=3, black cells at (3,3) only. Then min_row=3,max_row=3,min_col=3,max_col=3, span=1, required_side=1. Placement: any 1x1 square covering (3,3) exists? Square at (3,3) size1 is valid because r=3 <= n-D+1=3, c=3 <= m-D+1=3. So feasible. So cost=1-1=0? But note: initially black cell at (3,3). To have a square of side 1, we need that all black cells are exactly that square. That square would be cell (3,3). All black cells are that cell. No other black cells. So condition satisfied: cells outside square are white (none are black). So cost=0? Wait, is that allowed? The problem says "paint minimum possible number of white cells with black so that all black cells form a square." If the black cells already form a square, we don't need to paint any. So answer should be 0. But does the problem allow 0? In examples, they gave a case where all white gave 1. But they didn't show a case with existing square. Typically answer can be 0. Let's verify: In input like:
1 1
B
Then we have a square of side 1 already, so answer 0. Let's see if constraints allow: "minimum possible number of white cells needed to be painted black" - if no painting needed, then 0. So yes.
But check note: "The square's side should have positive length." That's fine.
Thus algorithm: If B == 0, answer = 1 (since we must create a square, we paint one white cell). If B > 0:
Compute min_i, max_i, min_j, max_j.
Let d = max(max_i - min_i + 1, max_j - min_j + 1).
If d > n or d > m: then impossible because square can't fit in grid? Actually d could be <= n and <= m? Wait: we need to check if we can place a square of side d inside grid. That requires d <= n and d <= m. If either condition fails, then impossible. But even if d <= n and d <= m, we must also check that there exists a placement that covers all black cells. However, if d <= n and d <= m, is it always possible to place such a square covering the bounding box? Because we need to find r in [max_i - d + 1, min_i] and c in [max_j - d + 1, min_j] that also satisfy r >= 1, r <= n-d+1, c >=1, c <= m-d+1. Since d <= n and d <= m, the intervals for r and c that keep the square inside are [1, n-d+1] and [1, m-d+1]. The needed r range is [max_i - d + 1, min_i]. For feasibility, we need intersection of [max_i - d + 1, min_i] with [1, n-d+1] to be nonempty. Similarly for columns.
Given that d is the max of the spans, we need to check if these intervals intersect.
Let r_min_needed = max_i - d + 1
Let r_max_needed = min_i
The feasible r range due to grid is [1, n-d+1].
We need r_min_needed ≤ r_max_needed (which is true because d >= max_i - min_i + 1 => d >= (max_i - min_i +1) => max_i - d + 1 ≤ min_i) Actually compute: max_i - d + 1 ≤ max_i - (max_i - min_i +1) + 1 = min_i. So yes r_min_needed ≤ r_max_needed holds because d is at least the row span. So the needed interval is non-empty.
But we need that this needed interval overlaps with [1, n-d+1]. Since needed interval is within [max_i - d + 1, min_i], we need that [max_i - d + 1, min_i] ∩ [1, n-d+1] ≠ ∅.
Given that the grid rows go from 1 to n. It's possible that needed interval lies entirely outside the feasible range. Example: n=5, d=5, black cells at rows 2..5? But then min_i=2, max_i=5. Row span =4, d must be max(row_span, col_span). Suppose col_span requires d=5. Then needed r: r_min_needed = max_i - d + 1 =5-5+1=1; r_max_needed = min_i =2. So needed r ∈ [1,2]. Feasible r range for n=5, d=5 is [1,1] (since n-d+1=1). Intersection = [1,1] which is nonempty. Good.
What about black cells near top? If black cells rows are 1..1, d determined by cols maybe > row span. For example, n=5, m=5, black cells at (1,5) only? Actually one cell: min_i=1, max_i=1, row_span=1, col_span maybe something else? But if only one cell, d=1, fine.
Maybe a scenario: n=3, m=3, black cells at (1,1) and (3,3). Then min_i=1, max_i=3, row_span=3; min_j=1, max_j=3, col_span=3 => d=3. needed r range: r_min_needed = max_i - d + 1 =3-3+1=1; r_max_needed = min_i =1 => r=1 exactly. Feasible r range for n=3,d=3: [1,1] => OK. So fits.
But can we construct a case where needed interval is completely outside feasible range? Suppose black cells in rows 4 to 5 (min_i=4, max_i=5) and n=5, but d is something like 3? But d must be at least row span which is 2. But maybe col_span is 3, so d=3. Then needed r: r_min_needed =5-3+1=3; r_max_needed = min_i=4 => r ∈ [3,4]. Feasible r for n=5,d=3: [1,3] (since 5-3+1=3). Intersection = r=3 is available, so OK.
Now consider if black cells are in rows 5 to 5 (only row 5) but d=4 because col_span is 4. Then needed r: r_min_needed =5-4+1=2; r_max_needed =5? Wait min_i=5 (since only row5) so r_max_needed=5. So needed r ∈ [2,5]. Feasible r for n=5,d=4: [1,2] (since 5-4+1=2). Intersection = [2,2] OK.
To push it out, we need that r_min_needed > feasible upper bound or r_max_needed < feasible lower bound. Since r_min_needed ≤ min_i, and feasible upper bound = n-d+1. Could r_min_needed > n-d+1? That would mean max_i - d + 1 > n - d + 1 => max_i > n. But max_i ≤ n because black cells within grid. So impossible. Similarly, could r_max_needed < 1? That would mean min_i < 1, impossible. So it seems that if d ≤ n and d ≤ m, the needed intervals always intersect with feasible ranges. Let's verify more systematically:
Given: d = max(row_span, col_span). Let row_span = max_i - min_i + 1 ≤ d. So max_i - d + 1 ≤ min_i - (d - row_span) maybe? But we need to check intersection with [1, n-d+1].
Lower bound of needed: L_needed = max_i - d + 1.
Upper bound of needed: U_needed = min_i.
Feasible lower bound: L_feas = 1.
Feasible upper bound: U_feas = n - d + 1.
We need L_needed ≤ U_feas and U_needed ≥ L_feas.
First: U_needed = min_i ≥ 1 always, so U_needed ≥ L_feas holds.
Second: L_needed ≤ U_feas? L_needed = max_i - d + 1. U_feas = n - d + 1. So we need max_i - d + 1 ≤ n - d + 1 => max_i ≤ n, which holds. So L_needed ≤ U_feas is always true. So indeed, if d ≤ n (ensuring U_feas is defined and >=1? Actually U_feas = n-d+1; for d ≤ n, U_feas >=1? If d=n, U_feas=1, ok. So condition holds.
Similarly for columns: Since max_j ≤ m, we get c needed interval overlaps.
Thus, if d ≤ n and d ≤ m, there is always a feasible placement? Let's test edge: n=2, m=5, black cells at rows 1..2 (span=2), cols 1..4 (span=4). Then d = max(2,4)=4. But n=2 < d? Actually n=2, d=4 > n, so fails d ≤ n. So impossible. So indeed the only condition for possibility is that the minimal side length d fits within the grid: d ≤ n and d ≤ m. Because if d fits, we can always place the square such that it covers black cells (as shown above). So algorithm reduces to:
- If B == 0: answer 1.
- else:
Compute row min, max, col min, max.
Let side = max(max_row - min_row + 1, max_col - min_col + 1).
If side > n or side > m: print -1.
else: print side * side - B.
But wait, there might be a nuance: The square must have sides parallel, but it could be placed not exactly aligning with the bounding box? The above argument uses the fact that we can place the square such that it covers the bounding box. But is it always possible to cover all black cells with a square of side = d, given d is the max of spans? Yes, because we can align the square to have its left/top edges such that it includes min_i and min_j while also covering max_i and max_j. But we need to make sure that we can shift the square within the grid while still covering. The required condition is that the square of side d must be placed so that its rows cover the interval [r, r+d-1] which must include [min_i, max_i]. This is possible if and only if the length of the interval needed (max_i - min_i + 1) is ≤ d and the distance from r to min_i and max_i can be accommodated. Given d ≥ row_span, we can set r anywhere from max_i - d + 1 to min_i. The width of this range is (min_i - (max_i - d + 1) + 1) = d - (max_i - min_i) ≥ 1. So there is at least one integer r satisfying. Also we need r between 1 and n-d+1. As argued, because max_i ≤ n and min_i ≥ 1, the range [max_i - d + 1, min_i] always lies within [1, n-d+1]? Actually we argued L_needed ≤ U_feas, but we also need that the entire interval [L_needed, U_needed] intersects [1, n-d+1]. Since L_needed could be less than 1? Possibly L_needed could be less than 1. Example: min_i=2, max_i=3, d=5 (due to col span). Then L_needed = max_i - d + 1 = 3-5+1 = -1. U_needed = min_i=2. The needed interval is [-1,2]. Intersection with [1, n-d+1]? n-d+1 might be negative if d>n, but here d=5 and n maybe 4? If d>n then we already declared impossible. If d ≤ n, say n=5, then U_feas = 5-5+1=1. Intersection of [-1,2] with [1,1] is [1,1], which is nonempty. So even if L_needed < 1, it's fine because we can pick r=1, which is within needed? Need to check: For a given r, condition is r ≤ min_i and r ≥ max_i - d + 1. If L_needed < 1, the lower bound is effectively 1 because r must be at least 1. So we need some r satisfying 1 ≤ r ≤ min_i and r ≥ max_i - d + 1. Since max_i - d + 1 ≤ 1 (because it's negative or <=0), the condition r ≥ that is automatically satisfied for r≥1. So we just need r ≤ min_i. Also need r ≤ n-d+1. So as long as there is r with 1 ≤ r ≤ min(min_i, n-d+1), we are okay. That is always true if min_i ≥ 1 and n-d+1 ≥ 1? But n-d+1 ≥ 1 because d ≤ n. Also we need r ≤ min_i; if min_i is at least 1, then r can be chosen as min(min_i, n-d+1). But we also need r ≤ n-d+1? Actually r must be ≤ n-d+1. So we need min(min_i, n-d+1) to be at least 1. Since both are at least 1, it's fine. However we also need to satisfy the condition for covering the top: r ≤ min_i is needed; and for covering bottom: r + d - 1 ≥ max_i => r ≥ max_i - d + 1. If we choose r = min(min_i, n-d+1), is it guaranteed that r ≥ max_i - d + 1? Since max_i - d + 1 might be > r? Let's check: r chosen as min(min_i, n-d+1). The worst case is r = n-d+1 if that is smaller than min_i. Then we need to verify that n-d+1 ≥ max_i - d + 1 => n ≥ max_i, which is true. So it's okay. Similarly, if r = min_i (if min_i ≤ n-d+1), then we need min_i ≥ max_i - d + 1 => d ≥ max_i - min_i + 1, which holds. So indeed there is always a valid r.
Therefore, the condition reduces to side ≤ n and side ≤ m.
But is there any scenario where we might need a larger side because the minimal side doesn't allow all black cells to be covered due to the fact that the square must be contiguous? No, a square is just a set of cells; covering means that each black cell's coordinates lie within the square's rows and columns. So it's just a rectangle inclusion condition. So the above is sufficient.
But wait: The problem states "All the cells that do not belong to the square should be white." That implies after painting, cells outside the square must be white. We cannot paint black cells white. So initial black cells outside the square are forbidden. So we require that there are no black cells outside the square. So indeed the square must contain all black cells.
But is there any additional constraint: "all black cells form a square" might be interpreted as the set of black cells exactly equals the set of cells in the square, i.e., there should be no missing black cells inside the square? Actually the condition "all black cells form a square" could be read as: The black cells, considered as a set, form a square shape (i.e., they are exactly the cells of some square). So if there is a missing black cell inside the square (i.e., a white cell inside the square that we didn't paint black), then the set of black cells would not be the entire square; there would be a hole. However, the phrase "all black cells form a square" could be ambiguous: Does it require that the black cells are exactly the square (i.e., contiguous block, no gaps) or simply that they are contained within a square and collectively they form a square shape? Usually in such problems, "form a square" means that the black cells constitute a solid square (i.e., all cells of some square are black, and no other cells are black). The note: "All the cells that do not belong to the square should be white." That's explicit: outside the square must be white. But it doesn't explicitly say that every cell inside the square must be black. However, if some cell inside the square were white, then that cell does not belong to the square? Wait, the square is defined as a set of cells. "All the cells that do not belong to the square should be white." That means cells outside the square must be white. It does NOT say that cells inside the square must be black. However, the phrase "all black cells form a square" suggests that the black cells collectively are in the shape of a square. If some cell inside the square is white, then the black cells would not be exactly the square; they would be a square with holes. Does that count as "forming a square"? Usually no: The black cells should be exactly a square, i.e., a filled square. The example: In first example, initial configuration had some black cells not forming a square. They painted additional cells to get a square. After painting, all cells inside the square are black, and outside are white. So indeed they made the whole square black. The output is the number of cells needed to be painted, which corresponds to turning white cells inside to black.
Thus the final set of black cells should be exactly a square region. So we must have all cells inside the square become black. So our interpretation is correct: we need to paint white cells inside the square to black. So final black cells = square cells. So cost = number of white cells inside square.
Thus algorithm as above.
But there is a nuance: Could there be a situation where B > 0 but side computed as above is 0? Not possible, since side is at least 1.
Now check example 1: Input:
5 4
WWWW
WWWB
WWWB
WWBB
WWWW
Let's list black cells: Row2 col4? Actually rows: row1: WWWW (no). row2: WWWB -> B at (2,4). row3: WWWB -> B at (3,4). row4: WWBB -> B at (4,3) and (4,4). So B=4. Compute min_row=2, max_row=4 => row_span=3. min_col=3? Actually columns: B at col4 (row2,3), col3 (row4), col4 (row4). So min_col=3, max_col=4 => col_span=2. So side = max(3,2)=3. Check if side fits: n=5,m=4 => side=3 ≤ 5 and ≤4, yes. Cost = 9-4=5. matches output.
Example2: 1 2, BB: B=2. min_row=1, max_row=1 => row_span=1. min_col=1, max_col=2 => col_span=2 => side=2. But n=1 <2, so impossible -> -1.
Example3: all white: B=0 => answer 1.
Seems consistent.
But consider a test case: n=2,m=2, grid:
B W
W W
Here B=1, min_row=1, max_row=1, min_col=1, max_col=1 => side=1. side fits, cost=1-1=0. Because existing black cell already forms a 1x1 square. So answer 0.
What about n=2,m=2:
B B
W W
B=2, positions: (1,1),(1,2). min_row=1,max_row=1=>span1, min_col=1,max_col=2=>span2 => side=2. side=2 ≤2 and ≤2, cost=4-2=2. But can we achieve a 2x2 square? The square would be the whole grid. We need to paint the two white cells black: (2,1),(2,2). So cost=2. But is there a possibility to have a 1x1 square? That would not contain all black cells because black cell at (1,2) would be outside if square is e.g. (1,1) only. So not allowed. So answer 2. That seems fine.
Now, is it always optimal to use side = max(span_rows, span_cols)? Suppose B>0, but maybe using a larger side could allow us to avoid painting some black cells? No, because painting more white cells increases cost, but we cannot avoid painting white cells inside the square. However, could there be a scenario where using a larger side reduces the number of white cells we need to paint? That seems counterintuitive: Larger square area means more cells to potentially paint black, so cost = area - B, which increases with area because B is constant. But wait, B is constant? If we choose a larger square, we might include additional black cells that were initially white? No, B is the total number of black cells in the whole grid. Those are all inside the square because we must include all black cells. So any square that includes all black cells must have area at least side^2, and B is fixed. So cost = area - B, which is monotonic increasing with side length. So the minimal side that can contain all black cells is optimal. So yes.
But is it possible that the minimal side based on spans cannot contain all black cells because the black cells are not contiguous? But containing them doesn't require contiguity; they just need to be within the square's rows and columns. So as long as the square covers the bounding rectangle, it contains them all. So yes.
Thus algorithm is straightforward. However, we should double-check the scenario where B=0. In that case, we don't have min/max coordinates. The problem states: The square's side should have positive length. We need to create a square. The cheapest is to paint one cell black to get a 1x1 square. So answer = 1. But what if n=0? Not possible because n,m≥1.
One might argue: Could there be a case where B=0 but the grid is such that we cannot place a 1x1 square? Since grid has at least 1 cell, we can. So answer 1.
But wait, what if B=0 and the grid is e.g., n=0? Not allowed.
Thus solution: read n,m, grid. Count black cells B, and record min_i, max_i, min_j, max_j. If B == 0: print 1. Else: d = max(max_i - min_i + 1, max_j - min_j + 1). If d > n or d > m: print -1. Else: print d*d - B.
But is there any scenario where d > n or d > m but there exists a larger square that fits? If d > n or d > m, that means the minimal side needed to cover the black cells is larger than one dimension of the grid, so it's impossible to place any square that contains them because any square containing them must have side at least d, and that can't fit. So -1.
Edge case: Suppose B>0, but the black cells are such that the bounding box's side length is, say, rows span=3, cols span=5, and n=5,m=4. Then d=5, but m=4, so impossible. Could we rotate the square? No, sides must be parallel. So -1.
Now, think about whether we must also ensure that after painting, all cells outside square are white. Since we cannot paint black to white, we must have initially no black cells outside. Our square selection includes all black cells, so that condition holds. However, could there be a scenario where the square contains all black cells but there is a black cell outside? No, because we include all black cells, so there are none outside. So fine.
One more nuance: The problem statement: "Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square." The phrase "all black cells" might refer to the final set of black cells after painting, not necessarily the initial black cells. So we are allowed to paint additional cells black. But we cannot change black to white. So final black cells = initial black cells ∪ painted cells. That set must be exactly a square. So indeed initial black cells must be a subset of the square, and painted cells are the complement of initial black cells within the square. So our logic holds.
Thus solution is simple.
But is there any tricky scenario where the minimal square covering all black cells cannot be used because some black cell lies on the boundary and the square might need to be placed such that the square includes it, but the square may have to be positioned to also include all cells and also not have any black outside? That's fine.
Let's test more cases mentally:
Case 1: n=3,m=3, grid:
B W B
W W W
W W W
Black at (1,1) and (1,3). B=2. min_row=1,max_row=1, min_col=1,max_col=3 => d = max(1,3)=3. Check fits: n=3,m=3 -> ok. cost = 9-2=7. But can we do better with a different placement? For instance, could we use a 2x2 square that contains both black cells? A 2x2 square covers a contiguous 2x2 block. To contain (1,1) and (1,3) simultaneously, the square would need to cover columns 1 to 3? A 2x2 square covers at most 2 columns, so cannot cover both columns 1 and 3. So indeed need side at least 3. So answer 7.
Case 2: n=3,m=3, grid:
B W W
W B W
W W B (diagonal). B=3. min_row=1,max_row=3, min_col=1,max_col=3 => d=3. cost=9-3=6. Could there be a 2x2 square containing all three? Possibly if they all lie within some 2x2? The points are (1,1),(2,2),(3,3). They are not all within any 2x2 contiguous block because the max row and col spread is 3. So need 3. So 6.
Case 3: n=3,m=4, grid:
W B W W
W W B W
W W W W
Black at (1,2) and (2,3). B=2. min_row=1,max_row=2=> span=2; min_col=2,max_col=3=> span=2; d=2. Check fits: n=3,m=4 => ok. cost=4-2=2. Square of side 2. Where could we place it? The needed r in [max_i - d +1 = 2-2+1=1, min_i=1] => r=1. c in [max_j - d +1 =3-2+1=2, min_j=2] => c=2. So square rows 1-2, cols 2-3. That contains both black cells. The other cells inside square: (1,3) is white? Actually (1,3) is W, (2,2) is W? Wait (2,2) is W? The grid: row2: W W B W so (2,2) is W. So we need to paint (1,3) and (2,2) black -> 2 cells. So cost 2. Good.
Now, what about situation where B=0, but we could paint more than one cell to form a larger square? The minimal is 1. So answer 1.
Edge: If n=1,m=1, grid: W. B=0 -> answer 1. If grid: B -> B=1 -> d=1 -> cost=0.
Now, we must confirm the condition that the square's sides are parallel to the painting's sides, which we assume.
Thus the solution seems trivial.
But wait, before finalizing, we need to double-check the logic about painting: The problem says "paint minimum possible number of white cells with black so that all black cells form a square." It doesn't explicitly say we cannot paint black cells white. Usually in such problems, you are only allowed to paint white cells black, not the reverse. However, could the interpretation be that we are allowed to repaint any cells, but we want to minimize the number of cells we change from white to black? The phrase "paint minimum possible number of white cells with black" suggests we can only paint white cells black. So indeed we cannot change black to white.
Thus our reasoning stands.
But there is also a possibility: The existing black cells might not be contiguous, but they might already be exactly a square (if they fill a square entirely). In that case, answer = 0.
Now, check if there is any scenario where the minimal side d based on spans might be less than the actual required side because the black cells might be arranged in such a way that a square of side d cannot contain them if we also require the square to be contiguous? Actually containing just means that for each black cell, its coordinates lie within the square's rows and columns. That is independent of contiguity. So if the black cells are within the rows and columns, they are inside the square. So if the bounding rectangle fits within the square, all black cells are inside. So d = max(width, height) ensures that the square can contain the bounding rectangle.
One might think: what if the black cells are not axis-aligned? They are axis-aligned positions. The bounding rectangle is the minimal axis-aligned rectangle containing them. Any square that contains that rectangle must have side at least max(width, height). And indeed there exists a square of that side that contains it (by aligning appropriately). So yes.
Thus the algorithm is correct.
But there is a subtlety: The problem statement says "paint minimum possible number of white cells with black so that all black cells form a square." Could "all black cells" refer to the cells that are black after painting? Yes. So we must ensure that after painting, the black cells exactly form a square. So we might consider that we could also choose to not include some initial black cells? No, because we cannot change black to white, so initial black cells remain black. So they must be part of the final square. So they must be within the square. So our condition stands.
Thus solution is straightforward.
Implementation details:
- Read n, m.
- Initialize B=0, min_row = INF, max_row = -INF, min_col = INF, max_col = -INF.
- Loop i from 1 to n, read each string.
- Loop j from 1 to m, if char == 'B', update variables and increment B.
- After loop:
- If B == 0: print 1.
- Else:
side = max(max_row - min_row + 1, max_col - min_col + 1).
If side > n or side > m: print -1.
else: print side*side - B.
Time complexity O(n*m). Memory O(1). Works.
But wait, check example 1 again: The answer is 5. Our calculation yields 9-4=5. So good.
Now, consider some edge cases to be absolutely certain:
Case: n=100,m=100, B=1 at (1,100). Then min_row=1,max_row=1,min_col=100,max_col=100 => side = max(1,1)=1, cost 0. But is there a 1x1 square that contains (1,100)? Yes, the square of side 1 at (1,100) is valid. So answer 0. But is it allowed that the square is just that one cell? Yes, side positive length. So 0.
Case: B=0, but maybe n=0? Not possible.
Now, what about constraints: n,m up to 100, so side up to 100, area up to 10000, B up to 10000, fits int.
Now, is there any hidden condition that the square must have side at most min(n,m)? We already check.
Double-check the condition about "All the cells that do not belong to the square should be white." That is automatically satisfied if no black cells outside. But what about after painting? We only paint white cells black, so we cannot make outside cells white. So initial outside black cells would remain black. So we must have zero initial black cells outside. So our square must cover all black cells. That's correct.
But what if there are black cells inside the square that are not part of the square? Actually if they are inside, they are part of the square; that's fine.
Now, can there be a situation where we could achieve a square by painting white cells black, but also maybe we could choose a square that doesn't include some initial black cells? No, because we can't change those black cells to white, so they must be part of the final black set. So they must be inside the square. So all initial black cells must be inside.
Thus the square must be a superset of the set of initial black cells.
Hence minimal square is indeed the minimal axis-aligned square containing all black cells.
Now, double-check the possibility of a square of side d being placed in multiple positions, but the cost (d^2 - B) is independent of position because B is total black cells and area is fixed. So no need to compute placement.
But wait, there is a nuance: Could there be a scenario where the minimal side d cannot be placed because the black cells' bounding rectangle forces the square to extend beyond the grid due to the required positioning? As argued earlier, if d ≤ n and d ≤ m, there is always a placement. Let's prove formally:
Given d ≤ n and d ≤ m.
Let r0 = max(1, max_i - d + 1) but also need r0 ≤ min_i and r0 ≤ n-d+1. We need to find r satisfying:
max_i - d + 1 ≤ r ≤ min_i,
1 ≤ r ≤ n-d+1.
So we need the intersection of intervals [max_i - d + 1, min_i] and [1, n-d+1] to be non-empty.
Since d ≤ n, n-d+1 ≥ 1.
Also max_i ≤ n, so max_i - d + 1 ≤ n - d + 1.
Also min_i ≥ 1.
Now we need lower bound L = max(max_i - d + 1, 1) and upper bound U = min(min_i, n-d+1). We need L ≤ U.
We know:
- L ≤ U ⇔ max(max_i - d + 1, 1) ≤ min(min_i, n-d+1).
We can check two cases:
Case 1: max_i - d + 1 ≤ 1. Then L = 1. We need 1 ≤ min(min_i, n-d+1). Since min_i ≥ 1 and n-d+1 ≥ 1, min(min_i, n-d+1) ≥ 1, so holds.
Case 2: max_i - d + 1 > 1. Then L = max_i - d + 1. We need max_i - d + 1 ≤ min(min_i, n-d+1). Since max_i - d + 1 ≤ min_i (because d ≥ row_span), and max_i - d + 1 ≤ n-d+1 because max_i ≤ n, it holds.
Thus L ≤ U always. So feasible r exists. Similarly for c.
Thus condition is just d ≤ n and d ≤ m.
Thus algorithm stands.
But wait: There is an alternative interpretation: Could we also consider that we are allowed to paint some black cells white? The problem says "paint minimum possible number of white cells with black". That explicitly states we only paint white cells black. So we cannot erase black cells. So our reasoning holds.
Thus answer seems straightforward.
Now, let's check the Codeforces problem "Black Square" maybe. I recall a problem like this: "Black Square" from Codeforces Round #... Actually there is a problem "A. Black Square" from Codeforces Round #... but that one is different (about pressing buttons). This one is probably from an older contest or maybe "Malevich's Black Square"? Actually I recall a problem: "B. Black Square" from Codeforces Round #471 (Div. 2)? Not sure. But I think the solution is indeed as described.
Nonetheless, I will double-check sample tests:
Sample 1: output 5, matches.
Sample 2: -1, matches.
Sample 3: 1, matches.
Now, think about some more testcases:
Test 1:
Input:
3 3
BBB
BBB
BBB
Output? B=9, min/max rows 1..3, cols 1..3, d=3, cost=9-9=0. So answer 0.
Test 2:
Input:
3 3
BBW
BBW
WWW
B=4? Actually row1: B B W -> two blacks at (1,1),(1,2). row2: B B W -> (2,1),(2,2). So B=4. min_row=1,max_row=2, min_col=1,max_col=2 => d=2. fits, cost=4-4=0. Indeed the black cells already form a 2x2 square. So answer 0.
Test 3:
Input:
3 3
BWW
WWW
WWW
B=1, d=1, cost=0.
Test 4:
Input:
3 3
BWW
WWW
WWB
B=2, min_row=1,max_row=3, min_col=1,max_col=3 => d=3, cost=9-2=7. Could we use a 2x2 square? For example, if we choose square covering rows 1-2, cols 1-2, it contains (1,1) but not (3,3). If we choose rows 2-3, cols 2-3, it contains (3,3) but not (1,1). So need 3. So 7.
Now, consider if B=0 and grid is 1x1, answer 1. That's fine.
Now, potential pitfalls: We need to handle B=0 separately because we can't compute min/max. Alternatively, we could treat min and max as undefined and just output 1. That's fine.
Edge: n=1,m=1, B=1 => d=1, cost=0.
Now, check if there is any scenario where d computed is 0? Not possible.
One more nuance: The problem states "paint minimum possible number of white cells with black so that all black cells form a square." Could there be a scenario where it's optimal to not use the minimal bounding square because we might be able to "move" the square to a different location that includes all black cells but with a smaller side? Wait, the side length is determined by the spread. If we move the square, the required side length to cover all black cells is at least the maximum of the horizontal and vertical spans. Because to cover all black cells, the square must cover the range of rows from min_i to max_i, so its vertical side must be at least max_i - min_i + 1. Similarly horizontal. So any square that contains all black cells must have side length at least D = max(row_span, col_span). So minimal possible side is D. So cannot be smaller. So our computed d is the minimal side length possible.
Thus the solution is correct.
Now, let's think about the possibility that there are no black cells initially, but we could create a square of side >1? That would cost more than 1, so minimal is 1.
Thus algorithm is final.
But wait, the problem statement: "The square's side should have positive length." That's satisfied.
Now, I'll provide a solution in Python.
Implementation:
def solve():
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
B = 0
min_r, max_r = n+1, 0
min_c, max_c = m+1, 0
for i in range(1, n+1):
line = input().strip()
for j, ch in enumerate(line, start=1):
if ch == 'B':
B += 1
min_r = min(min_r, i)
max_r = max(max_r, i)
min_c = min(min_c, j)
max_c = max(max_c, j)
if B == 0:
print(1)
return
d = max(max_r - min_r + 1, max_c - min_c + 1)
if d > n or d > m:
print(-1)
else:
print(d*d - B)
We should consider the case when B>0 but the computed d is maybe 0? Not.
Now, double-check with a test: n=2,m=2, B at (1,1) only. d=1, cost=0. So answer 0.
Now, test with n=2,m=2, B at (1,2) and (2,1). B=2. min_r=1,max_r=2 => row_span=2; min_c=1,max_c=2 => col_span=2; d=2; fits, cost=4-2=2. So answer 2. Could we form a square of side 2? Yes, whole grid, need to paint (1,1) and (2,2) black. So 2. Good.
Now, consider n=2,m=3, grid:
B B B
B B B
B=6. min_r=1,max_r=2 (span=2), min_c=1,max_c=3 (span=3) => d=3. But n=2, d=3 >2 so impossible? However, can we form a square? The black cells occupy a 2x3 rectangle, not a square. To get a square, we would need to have a 3x3 square, but grid is only 2 rows, so impossible. So -1. That seems plausible: We cannot expand the grid. So -1.
Thus algorithm seems consistent.
Now, I recall that there might be a similar problem where the answer could be -1 also when B > n*m? No.
Thus I'll produce final solution.
But before finalizing, I want to consider if there is any scenario where the minimal square containing all black cells might have side length less than the spans due to the ability to rotate the square? But sides must be parallel to painting's sides, so no rotation.
Thus final.
Now, let's think about a corner case: n=1,m=5, B=1 at column 3. Then d = max(1-1+1=1, 3-3+1=1) =1. d <= n? n=1, d=1 OK, cost=0. So answer 0. But is it allowed to have a square of side 1? Yes. So okay.
But if B=2 at columns 1 and 5? Then row_span=1, col_span=5 => d=5. But n=1, d=5 >1 so impossible -> -1. Indeed cannot cover both with a square because any square must have side at least 5, but grid only has 1 row, so impossible.
Now, confirm with sample 2: B=2, min_col=1,max_col=2 => col_span=2, d=2, n=1 -> impossible -> -1.
Thus correct.
Now, is there any case where d ≤ n and d ≤ m but still impossible because the square cannot contain all black cells due to positioning constraints? Let's try to construct a counterexample: Suppose n=3,m=3, black cells at (1,1), (1,3), (3,1), (3,3). This is four corners. Row span = 3 (1 to 3), col span = 3, d=3. d=3 fits exactly (n=m=3). We can place the 3x3 square covering entire grid. So it works. Suppose black cells at (1,2), (2,1), (2,3), (3,2) - a plus shape. Row span=3, col span=3, d=3, fits. So works.
Suppose n=3,m=4, black cells at (1,1), (3,4). Row span=3, col span=4 => d=4. But m=4, n=3, d=4 > n? 4 > 3, so fails. So -1.
Suppose n=4,m=4, black cells at (1,1) and (4,4). Row span=4, col span=4 => d=4 fits, square entire grid, cost 16-2=14.
Now, suppose n=4,m=5, black cells at (1,2) and (4,4). Row span=4, col span=3 (2 to 4) => d=4. n=4 ok, m=5 ok. Need square side 4. Feasible placement: we need r in [max_i - d +1 = 4-4+1=1, min_i=1] => r=1. So rows 1-4. c in [max_j - d +1 =4-4+1=1, min_j=2] => c can be 1 or 2? Actually c must satisfy 1 ≤ c ≤ min_j=2 and c ≥ max_j - d + 1 =1, so c can be 1 or 2. Also must be ≤ m-d+1 = 5-4+1=2. So c can be 1 or 2. If we choose c=1, square columns 1-4 contains column 2 and 4, but black cell at (1,2) is in column 2 (inside), black at (4,4) is column 4 (inside). So both are covered. Good.
Thus always feasible.
Thus final answer.
But wait: There's a nuance: "All the cells that do not belong to the square should be white." Could we achieve that by painting some white cells black and also maybe painting some black cells white? The problem statement only says "paint minimum possible number of white cells with black". It does not explicitly forbid painting black cells white. But the phrase "paint white cells with black" implies the only operation is to change white to black. Usually in such problems, you are only allowed to paint white cells black. If you were allowed to also paint black cells white, they would phrase "repaint cells" or "paint cells" generally. But here it's specific: "paint white cells with black". So we cannot change black to white.
Thus answer.
Now, I'll produce final solution with explanation.
One more thought: Could it be that sometimes the answer is -1 when there is no way to make a square even by painting additional white cells? For B>0, if d > n or d > m, then impossible. For B=0, always possible (since we can paint any cell). So no other impossible case.
Thus final.
But I'll check one more potential pitfall: Suppose B>0 and d fits, but the cost might be negative? That would be if area < B, but area = d^2, B ≤ d^2 because black cells are inside square? Wait, are we sure that B ≤ d^2? Since black cells are within the bounding box which is contained in the square, but we haven't yet chosen the square. However, we compute d as max of spans, but the square we will choose must contain all black cells. For a given d, we can choose a placement that contains all black cells. But before placement, black cells might be more spread out than d? No, d is defined as the max span, so the bounding box fits within a d x d square aligned appropriately. So yes, all black cells are inside that d x d region. So B ≤ d^2. Actually they could be exactly d^2, or less. So cost = d^2 - B ≥ 0.
But could it be that B > d^2? Not possible. So no negative.
Now, check: What if there is no black cell, we output 1, but maybe the grid is such that it's impossible to have a square because n=0? Not.
Now, finalize.
I think the solution is correct.
But wait, could there be a scenario where the minimal square containing all black cells has side d, but that square would require us to paint some cells that are outside the grid? No, because we ensure d ≤ n,m and we place it within grid.
Thus fine.
Now, I'll produce final answer with Python code.
Note: The constraints are small, so no need for optimization.
Now, let's reflect on the problem statement again: "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."
Interpretation is clear.
Thus I'll code.
Implementation details: We'll read lines, maybe there are spaces? No.
Edge: Input lines might have spaces? Usually not.
We'll use 0-index or 1-index. Use 1-index for clarity.
Pseudo:
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data: return
n = int(data[0]); m = int(data[1])
grid = data[2:] # each row string
B = 0
min_r, max_r = n+1, 0
min_c, max_c = m+1, 0
for i in range(n):
row = grid[i]
for j,ch in enumerate(row):
if ch == 'B':
B += 1
min_r = min(min_r, i+1)
max_r = max(max_r, i+1)
min_c = min(min_c, j+1)
max_c = max(max_c, j+1)
if B == 0:
print(1)
return
d = max(max_r - min_r + 1, max_c - min_c + 1)
if d > n or d > m:
print(-1)
else:
print(d*d - B)
We'll test with examples.
Test 1:
5 4
WWWW
WWWB
WWWB
WWBB
WWWW
B count: (2,4),(3,4),(4,3),(4,4) => B=4. min_r=2,max_r=4,min_c=3,max_c=4 => d = max(3,2)=3. d<=5 and <=4? m=4, d=3 <=4 ok. cost=9-4=5. prints 5.
Test 2:
1 2
BB => B=2, min_r=1,max_r=1,min_c=1,max_c=2 => d = max(1,2)=2, d>n? n=1, 2>1 => print -1.
Test 3:
3 3
WWW
WWW
WWW => B=0 => print 1.
All good.
Now, I'll include explanation in final.
But one more nuance: In the first example, they painted 5 cells and the square side is 3. Our algorithm gave 5. They painted (2,2),(2,3),(3,2),(3,3),(4,2). Our algorithm counted B=4, area 9, cost 5. That matches.
Now, is there any alternative approach that could yield lower cost? Suppose we consider not covering the minimal bounding square but perhaps a larger square that includes additional black cells? That would increase cost. So no.
Thus final answer.
Now, I'm going to produce final solution.
But before final, double-check that the square's side must be positive length; that's fine.
Also, note that in B=0 case, answer 1. But is there any scenario where it's impossible to have a square? For B=0, we can always create a 1x1 square. However, if the grid has zero cells? Not possible.
Thus done.
Now, I'll produce final answer with code.
Wait, there is a nuance: In B=0 case, could the answer be 0? The problem says we need to paint so that all black cells form a square. If there are no black cells initially, then the set of black cells is empty. Does an empty set form a square? The square's side should have positive length, so a square must have at least one cell. The empty set does not constitute a square of positive area. So we need to create a square by painting at least one cell black. So answer 1 is correct.
Now, think about whether there is any possibility to have a square with zero black cells? No.
Thus correct.
Now, finalize.
But I recall a Codeforces problem "Black Square" that had a twist: The square could be of any size, and you needed to find the minimal number to paint, but there was also a condition that the square's sides are parallel to the board. And the solution was exactly as described. However, I recall reading some editorial where they said "if the minimal side length is larger than n or m, output -1; else output side*side - countB". Yes.
Thus final answer.
Now, we should also consider a scenario where B>0 but the bounding box's dimensions are such that one dimension is zero? Not possible.
Now, finalize.
I'll produce final solution.
Implementation in Python.
Potential pitfalls: reading input with trailing newline, spaces, etc. Use sys.stdin.read() or sys.stdin.readline.
We'll just use sys.stdin.readline.
Now, final.
But wait, is there any scenario where the square cannot be placed because the black cells are not all within the square due to the fact that the square must be exactly the set of black cells? Actually we are allowed to paint white cells inside to become black. So as long as all black cells are inside, we can fill the rest. So good.
Now, finalize.
One more thought: The problem says "paint minimum possible number of white cells with black so that all black cells form a square." If we have black cells that already form a square shape but with holes (i.e., some interior white), is that considered forming a square? Typically, a square would be filled. For example, if we have black cells only on the border of a square, does that "form a square"? Usually no; they'd say "square frame" or something. The phrase "all black cells form a square" implies the shape of the set of black cells is a square. A hollow square is still a square shape? In terms of pixel art, a hollow square could be considered a square outline, but it's not a solid square. The problem's note: "All the cells that do not belong to the square should be white." That suggests the square is a region; the cells not belonging to that region are white. It doesn't say anything about the interior being all black; but if the region is defined as a square, then the cells belonging to the square are exactly those within the square. So to satisfy that all cells not in the square are white, and the black cells are exactly the square? Actually, the condition "all black cells form a square" might be interpreted as the black cells themselves, as a set, constitute a square shape. That means the set of black cells must be exactly a set of cells that forms a square (filled). But the phrasing "All the cells that do not belong to the square should be white." is a clarification: after painting, the cells outside the square are white. But it does not state that the cells inside the square must be black. However, if the black cells form a square, then the cells inside the square (the region) should be black because they are black cells. So indeed the square region must be entirely black. So our interpretation is consistent.
Thus final.
I'll now produce final answer with code and explanation. ```python
import sys
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
n = int(data[0])
m = int(data[1])
rows = data[2:2 + n]
B = 0
min_r, max_r = n + 1, 0
min_c, max_c = m + 1, 0
for i in range(n):
row = rows[i]
for j, ch in enumerate(row):
if ch == 'B':
B += 1
r, c = i + 1, j + 1 # 1‑based indices
if r < min_r:
min_r = r
if r > max_r:
max_r = r
if c < min_c:
min_c = c
if c > max_c:
max_c = c
if B == 0:
# No black cells → create a 1×1 square
print(1)
return
side = max(max_r - min_r + 1, max_c - min_c + 1)
if side > n or side > m:
print(-1)
else:
print(side * side - B)
if name == "main":
solve()