There is a haunted town called HauntedLand. The structure of HauntedLand can be thought of as a grid of size n * m. There is a house in each cell of the grid. Some people have fled from their houses because they were haunted. '.' represents a haunted house whereas '*' represents a house in which people are living.
One day, Devu, the famous perfumer came to town with a perfume whose smell can hypnotize people. Devu can put the perfume in at most one of the houses. This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues. Two houses are said to be a adjacent to each other, if they share a corner or an edge, i.e., each house (except those on the boundaries) will have 8 adjacent houses.
You want to save people from Devu's dark perfumery by sending them a message to flee from the town. So, you need to estimate the minimum amount of time Devu needs to hypnotize all the people? Note that if there are no houses inhabited by people, Devu doesn't need to put perfume in any cell.
Input
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of each test case contains two space separated integers n, m denoting the dimensions of the town.
For each of next n lines, each line has m characters (without any space) denoting a row of houses of the town.
Output
For each test case, output a single integer corresponding to the answer of the problem.
Constraints
1 ≤ T ≤ 20
Example
Input:
2
2 2
.
..
3 4
...
**.
...
Output:
1
2
Explanation
In the first example, it will take Devu one second for putting the perfume at the only house. So, the answer is 1.
In the second example, He will first put the perfume at the * at cell (1, 1) (assuming 0-based indexing).
Now, it will take Devu 1 secs to put perfume. In the next second, the perfume will spread to all of its adjacent cells, thus making each house haunted.
So, the answer is 2.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to find the minimal time Devu needs to hypnotize all people (i.e., cover all '' cells) with the perfume. Devu can put perfume in at most one house (any cell, haunted or not). It takes 1 second to put it. Then it spreads to adjacent cells (8-direction) each second. So the process is: at time t=0, we decide to start placing perfume. At time 1, the perfume is placed in the selected cell. Then it spreads: after 1 second from placement (so at time 2), the neighbors are covered; after 2 seconds, the neighbors' neighbors are covered, etc. So the total time to cover a cell depends on its Chebyshev distance (max of dx, dy) from the source cell plus 1 (for placement). Actually, careful: if we start at time 0, placing takes 1 second, so at time t=1, the source cell is covered. Then at each integer time step, the perfume expands one Chebyshev step (since 8-direction adjacency, distance metric is Chebyshev distance). So a cell at Chebyshev distance d from source becomes covered at time = 1 + d. The process ends when all '' cells are covered. So the total time needed given source cell (i,j) is max_{(x,y) with ''} (1 + Chebyshev distance between (i,j) and (x,y)). So total time = 1 + max distance over '' cells. However, Devu can choose not to put perfume if there are no '', then answer 0. So we need to minimize over all cells (i,j) (any cell, including those that are '.' or '') of (1 + max distance to all '' cells), where distance is Chebyshev distance: d((i,j),(x,y)) = max(|i-x|, |j-y|). But is it always optimal to put perfume in a cell that is either '' or '.'? Yes, any cell.
Thus the problem reduces: Given a set of points (the '' cells) on a grid, find the minimal possible value of 1 + r, where r is the Chebyshev radius needed to cover all points, i.e., minimal over center c of max_{p in set} Chebyshev distance(c,p). The Chebyshev radius (the smallest r such that a Chebyshev ball of radius r covers all points) is the minimal possible maximum distance. Then answer = 1 + that radius. But we must consider that placing perfume takes 1 second, which is added. So answer = minimal r_center + 1? Actually if we define r = min_{center} max_{p} d(center,p). Then with that center, total time = 1 + r. So answer = 1 + r. So we need to compute the Chebyshev 1-center (minimizing the maximum Chebyshev distance) for a set of points in the plane (discrete grid, but center can be any cell, integer coordinates). Since the grid is discrete (n x m), we can restrict center to integer coordinates? Possibly optimal center could be at non-integer positions? Because Chebyshev distance is based on max absolute difference, the minimax center for Chebyshev distance among points with integer coordinates is actually the center of the minimal enclosing axis-aligned square (rotated 45? Actually Chebyshev ball is a square axis-aligned? In Chebyshev metric, balls are squares aligned with axes? Let's recall: Chebyshev distance: d((x1,y1),(x2,y2)) = max(|x1-x2|, |y1-y2|). The ball of radius r around (cx,cy) is all points with |x-cx| <= r and |y-cy| <= r, i.e., an axis-aligned square of side 2r. So the minimal r such that a square of side 2r centered at (cx,cy) covers all points. The problem is: given a set of points, find the smallest square (axis-aligned) that contains them, and then we can choose the center as the center of that square. But we are allowed to choose any center, but the Chebyshev radius needed will be half the side length of the minimal axis-aligned square covering all points, but note that the square can be placed with its center anywhere; the minimal possible max distance is the minimal radius r such that there exists a point (cx,cy) with all points satisfying |x_i - cx| <= r and |y_i - cy| <= r. That is equivalent to: we need to find the smallest r and center such that the intervals [cx - r, cx + r] contain all x_i and [cy - r, cy + r] contain all y_i. So the constraints are: r >= (max x_i - min x_i)/2? Actually if we can choose cx arbitrarily, then the condition is that the range of x_i must be contained in an interval of length 2r. So minimal possible r for x dimension is (max x_i - min x_i)/2. Similarly for y dimension, minimal r is (max y_i - min y_i)/2. And since the Chebyshev distance uses max of both, we need r >= max( (range_x)/2, (range_y)/2 ). Moreover, we can choose cx anywhere between min and max, ideally the midpoint, to achieve r = range_x/2. But if range_x is odd? Since coordinates are integer, range_x = max_x - min_x. For Chebyshev distance, if we place center at ( (min_x+max_x)/2, (min_y+max_y)/2 ), the distance to the extremes is max(|max_x - cx|, |min_x - cx|) = max( max_x - cx, cx - min_x). If we choose cx = (min_x+max_x)/2, then the distance = (max_x - min_x)/2 if range even, or ceil(range_x/2) if range odd? Actually if range_x = 5, min=0, max=5. Midpoint = 2.5. But if center must be integer? Is center required to be an integer cell? Because Devu can put perfume only in a house (cell), i.e., integer coordinates (row and column indices). So center must be an integer coordinate. Therefore we need to consider that center is restricted to integer grid points. In that case, the minimal max Chebyshev distance to all points (covering all '') from an integer center might be slightly larger than the continuous optimum (which is half the max of ranges). So we need to compute: r_min = min_{(cx,cy) in Z^2} max_{(x,y) in stars} max(|x-cx|, |y-cy|). Then answer = r_min + 1.
This is essentially the problem of finding the 1-center under Chebyshev distance for a discrete set of points, with center constrained to integer grid. Since the grid size is up to? Not given, but T up to 20. n and m? Not in problem statement? Possibly up to large? But typical for such problems, n,m could be up to maybe 10^5? Not likely; grid is described as n*m houses. In many problems, n,m can be up to 10^3 or 10^4. But we need to compute efficiently.
We can note that the function f(cx,cy) = max_{(x,y)} max(|x-cx|,|y-cy|) is convex (like L_inf norm). The minimal value on integers can be found by considering the extremes: It's like the smallest square (axis-aligned) with integer center covering all points. We can think of it as: Let min_x = X_min, max_x = X_max; min_y = Y_min, max_y = Y_max. For a given candidate radius r, we need to know if there exists an integer center (cx,cy) such that for all points, |x - cx| <= r and |y - cy| <= r. This is equivalent to: cx must be in the interval [x_i - r, x_i + r] for all i, i.e., intersection of all such intervals: cx must be in I = [X_min - r, X_max + r]? Actually for each point, the allowable cx is [x_i - r, x_i + r]. The intersection over all points is [max_i (x_i - r), min_i (x_i + r)]. This intersection is non-empty if max_i (x_i - r) <= min_i (x_i + r). Similarly for cy. And we need integer cx,cy. So the condition for existence of integer center is that the integer lattice point exists within the intersection rectangle? Actually we need both cx and cy to be integers, but they are independent: we can choose cx from its allowed integer set, and cy from its allowed integer set. So the existence condition is that there exists integer cx satisfying L_x <= cx <= R_x, and integer cy satisfying L_y <= cy <= R_y, where L_x = max_i (x_i - r), R_x = min_i (x_i + r), and similarly for y. So as long as ceil(L_x) <= floor(R_x) and ceil(L_y) <= floor(R_y), an integer center exists.
Thus we can binary search on r (minimum possible radius). Since r is at most max(n,m) maybe up to 10^5? Actually n,m could be up to maybe 2000? But we can compute directly without binary search if we think about the minimal r as max(ceil(range_x/2), ceil(range_y/2))? But careful: With integer center, is r_min = max( ceil((X_max - X_min)/2), ceil((Y_max - Y_min)/2) )? Let's test. Suppose we have points at x=0 and x=5. Then range_x=5. The continuous optimum r = 2.5, but integer center possible? If we choose cx=2, then distances: to 0:2, to 5:3 -> max=3. If cx=3, distances: to 0:3, to 5:2 -> max=3. So minimal max distance = 3 = ceil(5/2) = ceil(2.5)=3. So r_min = ceil(range_x/2). Similarly for y. And overall r_min = max(ceil(range_x/2), ceil(range_y/2)). Is it always that simple? Consider if points are not symmetric, e.g., x: 0,1,10. Then min_x=0, max_x=10, range=10, ceil(10/2)=5. Is there an integer center achieving max distance 5? If we set cx=5, distances: to 0:5, to 1:4, to 10:5 => max=5. So works. If cx=5 works. So seems plausible that the optimal integer center is the integer rounding of the midpoint. But we need to also consider both dimensions together: we need a single center (cx,cy) that works for both dimensions simultaneously. Since the constraints are independent (cx only depends on x coordinates, cy on y), the existence condition for given r is that the intervals for cx and cy are each non-empty with integer points. The minimal r is the smallest r such that both ceil(L_x(r)) <= floor(R_x(r)) and similarly for y. Because we can choose cx independently of cy. So the minimal r is the maximum of the minimal r needed for x alone and for y alone? Not exactly: The minimal r such that both intervals contain an integer may be the maximum of the separate minimal r_x and r_y, because if we increase r, both intervals widen. So indeed r_min = max( r_x_min, r_y_min ), where r_x_min is minimal integer r such that the integer cx exists: i.e., we need r >= ceil((X_max - X_min)/2) as argued? Let's compute L_x(r) = X_max - r? Wait: For all points, the condition is max_i (x_i - r) <= min_i (x_i + r). Since max_i (x_i - r) = X_max - r? Actually max over i of (x_i - r) = (max_i x_i) - r = X_max - r. Similarly min_i (x_i + r) = X_min + r. Wait careful: For each point x_i, the condition for cx is x_i - r <= cx <= x_i + r. The intersection of all these intervals is [max_i (x_i - r), min_i (x_i + r)] = [X_max - r, X_min + r]? Because max of (x_i - r) occurs at the largest x_i, so that is X_max - r. And min of (x_i + r) occurs at the smallest x_i, so that is X_min + r. So the intersection is [X_max - r, X_min + r]. It is non-empty if X_max - r <= X_min + r, i.e., r >= (X_max - X_min)/2. So continuous condition: r >= range_x/2. For integer cx, we need an integer in that interval. The interval length = (X_min + r) - (X_max - r) = 2r - (X_max - X_min) = 2r - range_x. So for integer existence, we need the interval to contain at least one integer, which is equivalent to ceil(X_max - r) <= floor(X_min + r). That is the same as existence of integer k such that X_max - r <= k <= X_min + r. This holds if floor(X_min + r) >= ceil(X_max - r). Since X_min and X_max are integers, we can analyze. The minimal integer r such that an integer exists is r_x_min = ceil( range_x / 2 ). Let's check: For range_x = 5, we need r >= 2.5; r integer so r >=3. Does r=3 work? Interval: [X_max-3, X_min+3] = [5-3=2, 0+3=3] => contains integer 2 or 3? Actually contains integers 2,3, so yes. r=2 gives interval [5-2=3, 0+2=2] => 3>2, empty. So minimal integer r is 3 = ceil(5/2). For range_x even: range_x=4, need r>=2; r=2 gives interval [max-2= (say 4-2=2), min+2=0+2=2] => contains integer 2, so works. ceil(4/2)=2, ok. So r_x_min = ceil(range_x/2). Similarly for y. Then overall minimal r = max( ceil(range_x/2), ceil(range_y/2) ). But is it always sufficient to take the coordinate center as some integer that satisfies both? Because we can choose cx as any integer in its allowed interval, and cy as any integer in its allowed interval. The intervals for cx and cy are determined solely by r. If we take r = max(ceil(range_x/2), ceil(range_y/2)), then both intervals contain at least one integer. However, do we need the same r for both dimensions? Yes, the same r is used for both coordinates. But if we take r larger than needed for one dimension, it only expands intervals, making integer existence easier. So there will be some integer cx and some integer cy. They may be chosen independently, so we can always pick a valid center. So r_min = max( ceil(range_x/2), ceil(range_y/2) ) indeed gives a feasible solution. Could there be a lower r? Suppose we try r less than that, then either for x dimension the interval is empty or no integer, so no cx exists. So that's minimal. So the minimal Chebyshev radius with integer center is indeed max( ceil((max_x - min_x)/2), ceil((max_y - min_y)/2) ). That seems straightforward.
But is that always the answer? Wait, we also need to consider that Devu can choose any cell, including those not containing people. So the set of points to cover are the '' cells. So we compute the axis-aligned bounding box of all '' cells. Let min_row = min i among '*', max_row = max i, similarly for columns min_col, max_col. Then compute row_range = max_row - min_row, col_range = max_col - min_col. Then r = max( ceil(row_range/2), ceil(col_range/2) ). Then answer = r + 1.
Let's test with the examples.
Example 1:
2 2
.
..
The only '' at (0,0) (if using 0-index). Then min_row=0, max_row=0, row_range=0, ceil(0/2)=0. min_col=0, max_col=0, col_range=0, ceil(0/2)=0. r=0. answer = 0+1=1. matches.
But wait, are there any edge cases? The spread includes corners, so Chebyshev distance is correct. But consider if there are no '*', answer should be 0. In that case, we treat as no need to put perfume. Our formula: if no stars, we can't compute min/max. So handle separately: if count=0 then output 0.
Now constraints: T up to 20, n,m not given but likely up to maybe 1000 or 10^4. But we just need to read grid and find min and max row and col among stars. So O(n*m) per test case, which is fine.
But before concluding, let's think about possible pitfalls: The grid is of size n * m. The rows and columns are indexed from 1 to n (or 0 to n-1) but that doesn't matter. The Chebyshev distance from a center to a star is max(|r - cr|, |c - cc|). That is correct for 8-direction adjacency. The spreading time from placement: after 1 sec, source cell covered. Then each second expands to neighbors, which after d seconds covers cells with Chebyshev distance d. So covering all stars requires at least 1 + max distance, as argued. And we want to minimize that by picking source. So indeed it's the 1-center problem. And as we derived, the minimal possible maximum Chebyshev distance is the minimal radius of a axis-aligned square covering all points, which is half the side length of the bounding box. The center can be anywhere within that square; if we restrict to integer centers, the minimal radius becomes ceil( range/2 ) for each dimension, and overall radius is the max of those. That yields the answer.
But wait, is it necessary that the bounding square be axis-aligned? Since Chebyshev balls are axis-aligned squares, yes. So the minimal covering square is axis-aligned. So the center is effectively the midpoint of the bounding box. That seems correct.
Let's test with a more complex configuration: Suppose stars are at (0,0) and (0,10). Then row_range=0, col_range=10. So r = max(ceil(0/2)=0, ceil(10/2)=5) =5. answer=6. Check: If we place perfume at row 0, col 5 (midpoint). Distances: to (0,0): |0-0|=0, |0-5|=5 => max=5; to (0,10): |0-0|=0, |10-5|=5 => max=5. So total time = 1+5 =6. Could there be a better center? If we place at row 0, col 4: distances: (0,0):4, (0,10):6 => max=6 => time=7. col5 is best. So answer 6 correct.
What about stars at (0,0) and (10,0). Similar. Works.
What about stars at (0,0) and (10,10)? Then row_range=10, col_range=10, r=ceil(10/2)=5 => answer=6. Center at (5,5) gives max distance 5. Good.
What about stars at (0,0), (0,1), (1,0), (1,1). Then row_range=1, col_range=1, r=ceil(1/2)=1 => answer=2. Place at (0,0): distances: max to (1,1) is 1? Actually Chebyshev distance = max(|1-0|,|1-0|)=1, so time=2. So answer=2. Could we do better with center (0,0)? time=2. Center (0,1): same. So 2 is minimal.
What about stars at (0,0) only? r=0, answer=1. That matches.
Now, consider scenario where stars are not forming a contiguous bounding box but with gaps. The farthest star distance is determined by extremes anyway. So formula seems robust.
But is there any scenario where the optimal center is not the midpoint of the bounding box because integer restriction might cause the needed radius to be larger than max(ceil(range_x/2), ceil(range_y/2))? Actually we argued that the minimal r is the smallest integer such that both intervals [X_max - r, X_min + r] and [Y_max - r, Y_min + r] contain an integer. That condition is exactly r >= ceil(range_x/2) and r >= ceil(range_y/2). But is that sufficient? For r = max(ceil(range_x/2), ceil(range_y/2)), both intervals contain at least one integer, but we need a single pair (cx,cy) such that cx is integer from first interval and cy integer from second interval. Since they are independent, we can pick any integer in each, so it's always possible. So yes, sufficient.
Thus answer is computed as described.
Potential pitfalls: Input sizes large but manageable. Note that we need to read lines with m characters, no spaces. Use fast I/O.
Edge case: only one star: r=0, answer=1. If no stars: answer=0.
Now, we must ensure that the formula works for all test cases. But I'm not 100% convinced because of a nuance: The spread of perfume is from one house to adjacent houses in one second. That includes diagonal adjacency. So Chebyshev distance is correct. However, there is also the 1 second for placing the perfume. So total time = 1 + max distance. That is correct if we start counting at time 0 and place at time 1. Alternatively, we could interpret: Devu puts perfume in at most one house, which takes one second. Then it spreads; the time to hypnotize all people is the time from start until all are hypnotized. So yes.
But maybe there's a twist: Devu can put perfume in at most one house, meaning he might choose not to put it at all. But if there are people, he must hypnotize them, so he needs to put it somewhere.
Now, check second example: They said he puts perfume at (1,1) assuming 0-based indexing. That is the * at row1 col1. Let's see distances: The farthest star? The grid has stars at (0,1), (1,0),(1,1),(1,2),(2,1). The Chebyshev distances from (1,1): max|dx|,|dy|: to (1,0):1, to (0,1):1, to (2,1):1, to (1,2):1, to (0,0?) no, but all covered. So max distance =1. So total time =1+1=2. That matches.
Thus solution seems trivial: compute bounding box, output max(ceil(row_range/2), ceil(col_range/2)) + 1 if any star, else 0.
But wait, is there a scenario where placing perfume not at the midpoint of the bounding box yields a smaller max distance because the bounding box might be larger than needed due to outliers? Actually the bounding box extremes define the farthest points in each direction; any center will have to cover those extremes. So the max distance is at least half of the width or height. The Chebyshev radius is determined by the extremes, not by interior points. So it's correct.
But, could the optimal center be outside the convex hull? In Chebyshev metric, the minimal radius is indeed given by the center of the minimal enclosing square, which may have its center outside the convex hull? For axis-aligned squares, the minimal square covering a set of points has its center at the midpoint of the min and max x and y, which lies inside the bounding box (the rectangle defined by min and max). That center is within the convex hull (maybe not inside but it's on line). So it's fine.
Now, the problem statement says: "Devu can put the perfume in at most one of the houses. This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues." So it's exactly as we thought.
Thus solution is O(n*m) per test case.
But we need to be careful about indexing: rows from 1..n, columns from 1..m. So row_range = max_row - min_row, col_range = max_col - min_col.
For i from 0 to n-1:
read line s of length m.
For j from 0 to m-1:
if s[j] == '*':
count++
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 count == 0: print 0
else:
row_range = max_r - min_r
col_range = max_c - min_c
r = max( (row_range + 1) // 2, (col_range + 1) // 2 ) # since ceil(a/2) = (a+1)//2 for integer a.
answer = r + 1
print answer
Let's test with examples:
Example 2: row_range = 2, col_range=2 => (2+1)//2 = 1 for both => r=1 => ans=2. Good.
Now consider row_range=3 => (3+1)//2=2 => ceil(1.5)=2, correct.
So formula works.
But wait, is there any scenario where the answer could be less than this due to the fact that Devu could put perfume in a house that is not exactly at integer coordinates? No, must be integer.
Now, I'd like to double-check with some more complex example to ensure no oversight.
Consider grid 1x5: "* * . * " Actually let's set positions: (0,0) '', (0,4) '', and also (0,2) ''. Then min_c=0, max_c=4 => col_range=4, (4+1)//2=2 => r=2 (since row_range=0). answer=3. Check: If we put perfume at col2 (center of bounding box). Distances: to col0:2, to col4:2 => max=2 => time=3. Could there be a better center? col2 gives distance 2. col2 is star? yes. If we put at col1: distances: to col0:1, to col4:3 => max=3 => time=4. col3 similarly. So 3 is optimal. So formula works.
Consider scenario where stars are at (0,0) and (1,2). Then min_r=0, max_r=1 => row_range=1 => ceil(1/2)=1. min_c=0, max_c=2 => col_range=2 => ceil(2/2)=1. So r=1, answer=2. Check: Is there a center that gives max distance 1? We need cx,cy such that max(|0-cx|,|0-cy|) <=1 and max(|1-cx|,|2-cy|) <=1. That means |0-cx|<=1 and |0-cy|<=1 -> cx in [-1,1], cy in [-1,1] (but we can restrict to grid? center can be any cell, so integer). Also for second: |1-cx|<=1 => cx in [0,2]; |2-cy|<=1 => cy in [1,3]. Intersection of cx intervals: from first: cx in [-1,1] (but integer maybe 0,1?), from second: [0,2] => intersection integer {0,1}. For cy: from first: cy in [-1,1] => possible -1,0,1; from second: [1,3] => intersection integer {1}. So we can pick cx=0 or 1, cy=1. For example (0,1): distance to (0,0): max(0,1)=1; to (1,2): max(1,1)=1. So works. So answer=2.
Now consider case where row_range is much larger than col_range: e.g., stars at (0,0) and (10,0). row_range=10, col_range=0. Then r = max(ceil(10/2)=5, 0)=5, answer=6. Center at (5,0) works.
Now, is there any scenario where the minimal r is not simply max of half ranges because the center must be integer and the intervals for x and y may not have an integer simultaneously if the required r is exactly the max of half ranges, but there might be a conflict? For example, suppose range_x = 1, range_y = 1, r=1 works. But suppose range_x=1, range_y=1, and the integer intervals for cx and cy might be such that there is no integer pair that satisfies both? Let's test: points: (0,0) and (1,1). Then min_x=0, max_x=1 => range_x=1 => r_x_min=ceil(0.5)=1. Similarly range_y=1 => r_y_min=1. For r=1, intervals: cx in [max_x - r, min_x + r] = [1-1=0, 0+1=1] => [0,1] inclusive, integer {0,1}. cy interval similarly [0,1] integer {0,1}. So many combinations. (0,0) gives distance to (1,1) = max(1,1)=1. So works. So no conflict.
But suppose points: (0,0), (0,1), (1,0). Actually min_x=0, max_x=1, min_y=0, max_y=1, ranges 1 and 1. For r=1, intervals same. Center (0,0) gives max distance to (1,0):1, to (0,1):1, ok.
Thus no conflict.
Consider case where range_x=0, range_y=1. Then r=1. cx interval: since min_x = max_x = a, interval = [a-1, a+1] includes integer a. cy interval: [max_y - 1, min_y + 1] = [b_max-1, b_min+1] =? For range=1, say min_y=0, max_y=1 => interval [0, 1]? Actually compute: cy in [max_y - r, min_y + r] = [1-1=0, 0+1=1] => [0,1] integer. So center (a,0) works? Distances: to (a,0):0; to (a,1):1 => max=1. So ok.
Thus formula holds.
Now, might there be a scenario where the optimal radius is less than max(ceil(range_x/2), ceil(range_y/2))? That would require that for one dimension the needed half-range is smaller because we can shift the center in that dimension to not be exactly midpoint? But the needed r for covering all points in x dimension is at least ceil(range_x/2) as we derived because the condition for cx existence is r >= ceil(range_x/2). So can't be less. So it's a lower bound. So the minimal r is at least that maximum. And we have a construction achieving that maximum. So it's optimal.
Thus solution seems trivial.
But before finalizing, let's ensure that there is no misinterpretation about the spread time: "the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues." Does it spread simultaneously to all adjacent? Yes, typical BFS. So after k seconds from placement, all cells with Chebyshev distance <= k are covered. So indeed.
One more nuance: The problem statement says: "Devu can put the perfume in at most one of the houses. This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues." It says "the perfume spreads from one house to all its adjacent houses in one second". Could it be that the spread is sequential? I.e., from the original house, after one second it spreads to its adjacent houses; then from those houses, in the next second each spreads to their adjacent houses, etc. That's exactly BFS. So correct.
Thus answer is as computed.
But wait, let's double-check the example second: They say: "He will first put the perfume at the * at cell (1, 1) (assuming 0-based indexing). Now, it will take Devu 1 secs to put perfume. In the next second, the perfume will spread to all of its adjacent cells, thus making each house haunted." So in total 2 seconds. Yes.
Now, is there any possibility that putting perfume in a house that is not in the bounding box could reduce the maximum distance? Consider points forming an L shape: e.g., stars at (0,0), (0,10), (10,0). The bounding box: min_x=0, max_x=10, min_y=0, max_y=10, ranges 10,10 => r=5, answer=6. Could we do better by placing center at (5,5)? distances: to (0,0):5, to (0,10): max(5,5)=5? Actually |0-5|=5,|10-5|=5 =>5, to (10,0):5 =>5. So time 6. What about center at (0,5)? Distances: to (0,0):5, to (0,10):5, to (10,0): max(10,5)=10 => time 11. So not better. So bounding box center is best.
Thus the solution is extremely simple.
But maybe the problem is more subtle because the grid boundaries exist? The perfume can spread only within the grid? Actually the grid is the town. Houses exist only within the grid. The perfume spreads to adjacent houses; if a house is on the boundary, it has fewer adjacent houses. But that doesn't affect the Chebyshev distance because we only need to cover the existing '*' cells, which are within the grid. The center must be a house in the grid; but our computed center might be outside the grid? Wait, we assumed center can be any integer coordinate, but we must consider that the grid is limited to rows 0..n-1, columns 0..m-1. Devu can only place perfume in a house that exists, i.e., within the grid. However, our derived center (cx,cy) from intervals may be outside the grid? Let's analyze: The intervals for cx and cy are derived from the stars' coordinates. Since stars are within the grid, the intervals [X_max - r, X_min + r] will definitely include points inside the grid? Not necessarily. For example, consider a star at (0,0) only. Then r=0, center must be (0,0) which is in grid. Good. For stars at (0,0) and (0, m-1) where m is large. Suppose n=1, m=100. Then min_x=0, max_x=0? Actually rows: all stars are at row 0. So row_range=0 => r_x_min=0. col_range = (m-1)-0 = m-1. r = ceil((m-1)/2). Then intervals: cx: [0-0? Actually row interval: [max_row - r, min_row + r] = [0 - r, 0 + r] = [-r, r] but row only 0? Actually r is large, say m-1=99 => r=50. So cx can be from -50 to 50. But grid rows only 0..0? Actually n=1, rows indices 0 only. So we must pick a cx that is within the grid (0..n-1). So we need not only that an integer exists in the interval, but also that it lies within the valid grid coordinates. Similarly for cy: interval [max_col - r, min_col + r] = [99 - 50 = 49, 0 + 50 = 50] => [49,50], so cy integer can be 49 or 50. But grid columns are 0..99. So 49 is okay, 50 is okay. But cx interval includes 0, which is valid. So we can pick cx=0, cy=49 or 50. That works. But is it always possible to choose a center within the grid? The problem states Devu can put perfume in at most one of the houses, meaning any house in the town. So the center must be a cell within the grid. So we need to ensure that there exists a grid cell (i,j) with 0<=i<n, 0<=j<m such that max(|i - star_row|, |j - star_col|) <= r for all stars, where r = max(ceil(row_range/2), ceil(col_range/2)). We assumed we can pick any integer from intervals. But those intervals may include integers outside the grid. However, are we guaranteed that at least one integer within the grid exists? Not necessarily. For instance, consider stars concentrated near one corner of the grid, and the grid is small, but the computed center might be outside. But the center must be within grid, so we might need a larger r to cover all stars from a permissible center. Let's test a scenario: Grid n=3, m=3. Stars at (0,0) and (0,2). Then min_row=0, max_row=0, row_range=0; min_col=0, max_col=2, col_range=2 => r = ceil(2/2)=1. So candidate r=1. Can we find a cell within 3x3 such that max distance to both stars <=1? That means we need cx,cy such that |cx-0|<=1 and |cy-0|<=1 and |cy-2|<=1 => cy in [0,1] from first? Actually first: |cy|<=1 => cy in [ -1,1 ] but grid only 0..2, so cy in [0,1] possibly. Second: |cy-2|<=1 => cy in [1,3]. Intersection => cy = 1. cx: from both: |cx|<=1 => cx in [-1,1]; but grid rows 0..2, so cx can be 0 or 1? Actually cx must be integer and within grid. cx in [-1,1] intersects with {0,1,2} yields cx=0 or 1. So we can pick (0,1) or (1,1). Both are in grid. So works.
Now try stars at (0,0) and (2,0). n=3,m=3. min_row=0,max_row=2 => row_range=2 => r=ceil(2/2)=1. Similarly col_range=0 => r=1. Need cx,cy such that |cx|<=1 and |cx-2|<=1 => cx in [1,? Actually first: cx in [-1,1], second: |cx-2|<=1 => cx in [1,3], intersection cx=1. cy: |cy|<=1 => cy in [-1,1]; grid cols 0..2 => cy can be 0 or 1? Actually need cy within grid, so cy=0 or 1. But also cy must satisfy? Both stars have col 0, so only constraint is |cy|<=1 from first? Actually second also col 0 so same: |cy|<=1. So cy in [-1,1] intersect grid => 0,1. So we can pick (1,0) or (1,1). So works.
Now consider stars at (0,0) and (0,1) in a grid 1x2? n=1,m=2. Then min_row=0,max_row=0, row_range=0; min_col=0,max_col=1,col_range=1 => r=ceil(1/2)=1. For r=1, cx interval: [0-1=-1, 0+1=1] => includes 0 (since row only 0). cy interval: [max_col - r, min_col + r] = [1-1=0, 0+1=1] => [0,1] includes 0 or 1. So we can pick (0,0) or (0,1). Both in grid. So works.
Now consider a scenario where the computed center might be forced to be outside grid because the grid is not large enough to accommodate the necessary intervals? For example, stars at (0,0) only. r=0, center must be (0,0) which is in grid. So okay.
But could there be a case where the intervals intersect the grid but the integer points within intersection are not present? Suppose the grid is 1x1: only cell (0,0). If there is a star at (0,0), r=0, center (0,0) fine. If there are no stars, answer 0. So fine.
Consider stars at (0,0) and (0,2) in a grid that is only 1x3? n=1,m=3. Then we already considered works: center (0,1) works. So fine.
What about stars at (0,0) and (2,2) in a 3x3 grid. row_range=2, col_range=2 => r=1. Need cx,cy such that |cx|<=1, |cx-2|<=1 => cx=1; |cy|<=1, |cy-2|<=1 => cy=1. (1,1) is in grid. Works.
What about stars at (0,0) and (2,0) in a 3x1 grid? n=3,m=1. Then row_range=2 => r=1; col_range=0 => r=1. Need cx=1; cy such that |cy|<=1, but grid only col 0, so cy must be 0. So (1,0) works. Good.
Thus it seems the grid boundaries likely won't restrict because the stars are within the grid and the minimal covering square's center will lie within the convex hull of stars which lies within the grid? Not necessarily: Consider stars at (0,0) and (0,4) in a grid 1x5. The center (0,2) is within grid. Fine.
Consider stars at (0,0) and (4,0) in 5x1 grid, center (2,0) within grid. Fine.
Now consider stars at (0,0) and (0,4) in a grid that is 1x4? Actually if m=4, columns 0..3. But max_col=4 is out of grid! Stars are within grid, so max_col cannot exceed m-1. So if grid is 1x4, columns are 0..3, so cannot have star at col 4. So safe.
Thus the grid boundaries naturally contain the stars, and the computed center from intervals [max_x - r, min_x + r] will always be within the range of star coordinates extended by r. But that interval might extend beyond the grid, but the intersection with grid is non-empty? We need to verify that there exists some integer point within the grid that also lies in the intervals. Since the grid contains all stars, and the intervals contain the stars' coordinates? Actually for any point p, the interval for cx includes p.x? For a given r, the condition for covering all points from a center is that center lies within the intersection of squares. The center can be chosen anywhere within that intersection. The stars themselves are not necessarily within the intersection; but the intersection is guaranteed to be non-empty for r >= r_min. However, the intersection might be entirely outside the grid? Could that happen? Let's try to construct a counterexample. Suppose the grid is n=3,m=3, rows 0-2, cols 0-2. Stars at (0,0) and (2,2). r_min = 1. Intersection for x: [max_x - r, min_x + r] = [2-1=1, 0+1=1] => cx=1. So forced cx=1 which is inside grid (0-2). For y: same, cy=1. So (1,1) is inside grid. So okay.
What about stars at (0,0) and (0,2). r=1, cx interval: [0-1=-1,0+1=1] => includes 0,1. Grid rows are 0..2, so 0 and 1 are valid. cy interval: [2-1=1,0+1=1] => cy=1. So we need cy=1, which is in grid. So okay.
What about stars at (0,0) only. r=0, cx=0, cy=0, in grid.
It seems that because the stars lie inside the grid, the intervals for cx and cy will always intersect the grid, at least at the location of one of the stars? Not necessarily: Consider stars at (0,0) and (0,2) in a grid that has rows only 0..0 (n=1) and columns 0..1 (m=2)? But max_col=2 would be outside grid, so impossible. So stars must be within grid, so min and max coordinates are within [0,n-1] and [0,m-1]. For r = ceil(range_x/2) etc., the intervals might extend beyond the grid, but there will be at least one integer within the grid that lies in the interval because the stars themselves are within the grid and the intervals include the stars? Actually does the interval for cx include the stars' x coordinates? For a given star at x_i, the condition for covering it from center cx is |x_i - cx| <= r. So cx must be within [x_i - r, x_i + r]. The intersection of all such intervals is [X_max - r, X_min + r]. The star with X_max itself, its interval is [X_max - r, X_max + r]. The intersection is narrower. For r = ceil(range_x/2), the intersection might be a single point or a small interval. Does that point lie within the grid? The midpoint of X_min and X_max is (X_min+X_max)/2. Since X_min and X_max are within [0, n-1], the midpoint lies between them, so its coordinate is between 0 and n-1 inclusive. However, if range_x is odd, the midpoint is not integer; the intersection interval for cx is [ceil(midpoint?) Let's compute: For r = ceil(range_x/2), the interval [X_max - r, X_min + r] is guaranteed to contain at least one integer (by construction), but is that integer necessarily within [0, n-1]? Not necessarily, because the integer could be outside if the midpoint is near the boundary and range_x is large. Example: n=5, rows 0..4. Suppose stars at row 0 and row 4. range_x=4, r = ceil(4/2)=2. Intersection: [4-2=2, 0+2=2] => cx=2. That's within 0..4, fine. Suppose stars at row 0 and row 3. range_x=3, r= ceil(3/2)=2. Intersection: [3-2=1, 0+2=2] => interval [1,2]. Integers 1 and 2 are within 0..4. Suppose stars at row 0 and row 0? trivial. Suppose stars at row 0 and row 1: range=1, r=1. Intersection: [1-1=0, 0+1=1] => [0,1] within grid. Suppose stars at row 0 and row 2: range=2, r=1. Intersection: [2-1=1, 0+1=1] => 1 within grid. So seems always within the convex hull of the stars, which lies within the grid. But consider stars at row 0 only. r=0, intersection point is 0 within grid.
What about stars at row 4 only? r=0, intersection 4 within grid.
Now, could the intersection be forced to be at a row that is less than 0? For that to happen, we would need X_max - r < 0 while X_min + r also maybe negative? But if X_max is within grid, say X_max = 0? Then range_x = 0? Actually if min and max are both >=0, then X_max - r could be negative if r > X_max. But r = ceil(range_x/2). Since range_x = X_max - X_min, r is at most something. Could r be greater than X_max? For X_max small, range_x small, r small. For example, X_max=0, X_min=0 => r=0, so X_max - r =0. If X_max=0, X_min=0, r=0. So fine. If X_max=1, X_min=0 => range=1, r=1 => X_max - r = 0, fine. If X_max=0, X_min=1 cannot happen because min <= max. So X_max - r is always >= X_min? Actually X_max - r could be negative only if X_max < r. Could that happen? Suppose X_max = 1, range_x might be large? Let's compute: For a set of points, X_min and X_max are within [0,n-1]. r = ceil((X_max - X_min)/2). Since X_max <= n-1 and X_min >=0, r <= ceil((n-1)/2). So r can be up to about half of n-1. For X_max small, say X_max=1, then X_min could be 0, range=1 => r=1 => X_max - r =0, non-negative. If X_min=1, then range=0 => r=0 => X_max - r =1. So X_max - r is always >= X_min? Actually X_max - r >= X_min? Because from the inequality: r >= (X_max - X_min)/2, so 2r >= X_max - X_min => X_max - r <= X_min + r, which is the condition, but we can examine sign: Since X_min >=0, and r >=0, X_max - r could be negative if X_max < r. Is it possible that X_max < r? For X_max < r, we would need r > X_max. But r = ceil((X_max - X_min)/2). Since X_min <= X_max, the maximum possible r given X_max is when X_min = 0, then r = ceil(X_max/2). Then X_max - r = X_max - ceil(X_max/2). For X_max=1, ceil(0.5)=1 => 1-1=0. X_max=2 => ceil(1)=1 => 2-1=1. X_max=3 => ceil(1.5)=2 => 3-2=1. X_max=4 => ceil(2)=2 => 4-2=2. So X_max - r = floor(X_max/2) for X_max even? Actually for X_max even, r = X_max/2, so X_max - r = X_max/2 >=0. For X_max odd, r = (X_max+1)/2, then X_max - r = (X_max -1)/2 >=0. So X_max - r is always >= 0 because r <= X_max for X_max >=0? Let's test X_max=0, r=0 => 0. So indeed, X_max - r is always >=0 because r <= X_max when X_max>=0? Check X_max=1, r=1 => 1-1=0. X_max=2, r=1 => 2-1=1. X_max=3, r=2 => 3-2=1. So yes, r <= X_max? For X_max=1, r=1 equal; X_max=2, r=1 <=2; X_max=3, r=2 <=3; X_max=4, r=2 <=4. So r <= X_max when X_max >=0? Let's prove: r = ceil((X_max - X_min)/2). Since X_min >=0, X_max - X_min <= X_max, so (X_max - X_min)/2 <= X_max/2, so ceil <= ceil(X_max/2) <= X_max for X_max >=0? Actually for X_max=0, ceil(0)=0; for X_max=1, ceil(0.5)=1 <=1; for X_max=2, ceil(1)=1 <=2; for X_max=3, ceil(1.5)=2 <=3; for X_max=4, ceil(2)=2 <=4. So indeed r <= X_max. Similarly, X_min + r <=? Not needed. So X_max - r >= 0. Similarly, Y_max - r >=0. Also, X_min + r may exceed n-1? Possibly, but we need a cx that lies within [0, n-1] as well. The interval [X_max - r, X_min + r] is guaranteed to contain integers; we need at least one integer that also satisfies 0 <= cx <= n-1. Since X_max - r >=0, the lower bound is at least 0. The upper bound X_min + r could be greater than n-1. But we can still pick cx as some integer in the intersection that also <= n-1 because the interval includes values <= X_min + r, but we can pick the smallest integer in the interval that is <= n-1. Since the interval includes X_max - r which is <= n-1 (because X_max <= n-1 and r>=0, so X_max - r <= n-1). So there is at least one integer in the interval that is <= n-1, namely the lower bound (if integer) or ceil of lower bound. However, we must also ensure that this integer is >=0, which is true as argued. So indeed there exists an integer within both the interval and the grid rows. More formally, let L = max(0, ceil(X_max - r))? Actually the integer points in the intersection that are valid in grid are those that satisfy max(ceil(L_x), 0) <= min(floor(R_x), n-1). Since L_x = X_max - r, R_x = X_min + r. We know L_x >=0, R_x >= L_x. Also, because X_max <= n-1, L_x <= n-1. And R_x could be > n-1, but the feasible integer set is [ceil(L_x), floor(R_x)] ∩ [0, n-1] = [ceil(L_x), min(floor(R_x), n-1)]. Since ceil(L_x) >=0 and ceil(L_x) <= n-1 (as L_x <= n-1), the set is non-empty as long as ceil(L_x) <= min(floor(R_x), n-1). Since ceil(L_x) <= floor(R_x) because interval non-empty, and ceil(L_x) <= n-1 because L_x <= n-1. So the intersection is non-empty. Similarly for columns. Thus there always exists a grid cell that serves as center achieving radius r. So the grid boundaries do not force a larger r. Therefore the formula is correct even with grid size constraint.
Thus answer is indeed r+1.
Now we just need to implement. Complexity: O(n*m) per test.
But wait: The input may be large. However, we can even compute without storing the grid: read line by line and update min/max.
Edge Cases: n,m could be up to 10^6? Not likely because input size would be huge (n*m characters). But maybe n,m up to 10^3 or 10^4, still okay.
Now, I want to double-check the problem statement for any nuance: "This takes Devu one second. Then, the perfume spreads from one house (need not be inhabited by people) to all its adjacent houses in one second, and the cycle continues." The phrase "from one house" might be ambiguous: Does it mean from the house where the perfume was placed, it spreads to its adjacent houses in one second, and then from those houses to their adjacent houses, etc. That's standard.
Another nuance: The perfume can be placed in at most one house. So if there are multiple houses, Devu may choose zero? Only if no people, then zero. So our answer covers that.
Thus solution is simple.
But given that this is a problem from some contest, perhaps there is a twist: The grid is of size n*m, and Devu can put perfume in at most one house. That is exactly one center.
Now, why would they ask such a trivial problem? Perhaps I'm missing something: Could the answer be something like the minimal time to cover all '*' cells might be less than 1 + Chebyshev radius because the perfume could be placed after some spread? No, the process starts with placement, then spread sequentially. The placement takes 1 second; after that, spread starts. So total time is 1 + distance (in steps) to farthest cell. There's no concurrency like placing multiple sources.
Maybe the catch is that the perfume spreads to all adjacent houses in one second simultaneously, which we accounted for.
Thus answer is straightforward.
But wait, the problem might be more interesting if the grid is large and we need to compute efficiently; but we already have O(n*m). Could there be a scenario where the answer is not simply derived from bounding box? Let's test with some random patterns. Suppose grid 3x3 with stars at corners: (0,0), (0,2), (2,0), (2,2). Then min_row=0, max_row=2, row_range=2, min_col=0, max_col=2, col_range=2, r=1, answer=2. Is there a center achieving max distance 1? Center (1,1) works: distances to corners =1. So answer 2.
Suppose stars at (0,0), (0,2), (2,0) only (missing (2,2)). Then min_row=0, max_row=2, row_range=2; min_col=0, max_col=2, col_range=2; r=1, answer=2. Center (1,1) gives distances: to (0,0)=1, (0,2)= max(1,1)=1, (2,0)=1. So works.
Now, consider stars that are not all within the bounding box? That's impossible.
Thus it's robust.
Hence we can implement.
But before finalizing, let's think: Could the answer be simply max( (max_i - min_i + 1)//2 + (max_j - min_j + 1)//2? No, we take max.
Now, check with some large values: For a single star, answer=1. Good.
Now, verify with a test where row_range=3, col_range=0: e.g., stars at rows 0,3 (in same column). Then r = ceil(3/2)=2, answer=3. Place center at row 1? Actually need to get max distance <=2: choose row 1? Distance to row3 =2, to row0=1 => max=2, works if column same. But row 1 is within grid? Assuming grid rows 0..3, yes. So time=1+2=3.
Now, consider stars at (0,0) and (3,3) in a 4x4 grid. row_range=3, col_range=3 => r=2, answer=3. Center at (1,1)? Distances: to (0,0):1, to (3,3): max(2,2)=2 => max=2 => time=3. Center (2,2) also works: distances 2 and 1? Actually (2,2) to (0,0):2, to (3,3):1 => max=2. So good.
Now, we need to output integer per test.
Now, let's read the problem statement again: "You want to save people from Devu's dark perfumery by sending them a message to flee from the town. So, you need to estimate the minimum amount of time Devu needs to hypnotize all the people? Note that if there are no houses inhabited by people, Devu doesn't need to put perfume in any cell."
Thus answer as we computed.
Now, I recall a known CodeChef problem "PERFCONT" or something? Actually there is a problem "DEVHAND" or "PERFUME"? Not sure. But this seems like a standard problem.
Given the simplicity, I'm comfortable.
But let's ensure we didn't misinterpret "adjacent" includes corners, which we used Chebyshev distance. If it were only 4-direction adjacency, the distance would be Manhattan or something else. But they explicitly said share a corner or an edge, i.e., 8-direction adjacency. So Chebyshev is correct.
Now, confirm with example: In second example, they put at (1,1) and in next second spread to all adjacent cells, which includes diagonals, so covers all stars. Indeed, all stars are within Chebyshev distance 1 from (1,1). So correct.
Thus solution: For each test case, if no '', print 0. Else compute min and max row and column of '', then answer = max( (max_row - min_row + 1) // 2, (max_col - min_col + 1) // 2 ) + 1.
Now, we need to be careful with integer division: ceil(a/2) = (a+1)//2 for integer a.
But note that row_range and col_range are differences, not lengths. For example, if min=0, max=2, range=2, (2+1)//2 = 1, correct.
Now, what about if min=0, max=3, range=3, (3+1)//2=2, correct.
Now, we should also consider that the grid indices are 0-based or 1-based? Doesn't matter because differences unaffected.
Implementation details:
We'll read T.
Loop T times:
read n,m
Initialize min_r = n, max_r = -1, min_c = m, max_c = -1, count = 0.
For i in range(n):
read line s (strip newline)
for j, ch in enumerate(s):
if ch == '*':
count+=1
if i < min_r: min_r=i
if i > max_r: max_r=i
if j < min_c: min_c=j
if j > max_c: max_c=j
if count == 0: print(0)
else:
row_range = max_r - min_r
col_range = max_c - min_c
r = max((row_range+1)//2, (col_range+1)//2)
print(r+1)
Now, test with given examples.
Example 1:
n=2,m=2
Row0: "*." -> star at (0,0): min_r=0,max_r=0,min_c=0,max_c=0
Row1: ".." -> none
row_range=0,col_range=0 -> r=0 -> ans=1. Output 1.
Example 2:
n=3,m=4
Row0: "..." -> star at (0,1)
Row1: "**." -> stars at (1,0),(1,1),(1,2)
Row2: ".*.." -> star at (2,1)
After processing all, min_r=0,max_r=2,row_range=2 -> (2+1)//2=1; min_c=0,max_c=2,col_range=2 -> (2+1)//2=1; r=1; ans=2.
Works.
Now, what about a test with no stars? For example, n=2,m=2, all '.' => count=0 => output 0. That's correct per note.
Thus solution done.
But wait, the problem might have intended that the perfume can be placed in a house that is haunted ('.') as well. Our approach includes that.
Now, let's consider if there is any scenario where Devu might not put perfume at the start? Actually he can put it at most one, and he would put it to hypnotize people. So he will put it at time 0? Actually we assume he starts putting at time 0 and finishes at time 1. That's the only action.
Now, some might argue that the total time might be 1 + distance, but if the farthest distance is 0, time=1. That's consistent.
Now, verify with a more complex case: Suppose grid 5x5, stars at (0,0) and (4,4). row_range=4, col_range=4, (4+1)//2=2 (since 5//2=2? Actually (4+1)//2=2.5? Wait integer: (4+1)//2 = 5//2 = 2 in integer division (floor). So r=2. Answer=3. Check: center (2,2) gives distances: to (0,0):2, to (4,4):2 => max=2 => time=3. Could there be a center giving max=2? Yes. Could we get r=2? Yes. Is there any better? If we center at (2,2) we get 2. Could we get 1? No because Chebyshev distance between the two stars is 4, any point can cover both only if distance <=? The minimum possible max distance is at least half the Chebyshev diameter? Actually the Chebyshev diameter (max distance between any two points) is 4. For any point, max distance to both is at least half the diameter? In Chebyshev, the minimal possible radius is exactly half the diameter? For two points, the minimal radius is ceil(d/2) where d is Chebyshev distance between them. Here d=4, half=2, so r=2. So good.
Now, if there are three points, the minimal radius is determined by the extreme points.
Thus solution stands.
Now, we must ensure we handle large input quickly. Use sys.stdin.read or sys.stdin.readline.
One more thought: Could the answer be simply the maximum of distances from the center chosen as the median? Not needed.
Now, let's think about potential pitfalls: The problem might require output for each test case an integer, and there is no mention of large constraints, but typical for CodeChef etc., n,m could be up to 10^9? That wouldn't make sense because the grid is given as characters. So n,m are moderate.
Now, a nuance: The spreading time is from one house to all its adjacent houses in one second, and the cycle continues. This implies that after each second, the perfume spreads to all houses that are adjacent to any house that already has perfume. That is indeed BFS, and the time to reach a cell equals its Chebyshev distance from the source, given that all edges have weight 1 and movement allowed in 8 directions. So our distance metric is correct.
Now, what about the fact that the perfume can be placed in a haunted house ('.')? That's allowed, we considered any cell.
Thus solution is complete.
Now, I'll produce final answer code in Python.
But before final, let's test a few more random cases with brute force for small grids to be absolutely sure. We'll write a small brute force that for a given set of stars, enumerates all possible centers, compute max distance, then take min, and compare with formula. I'll do mental.
Case: grid 2x3, stars at (0,0) and (0,2). Row_range=0, col_range=2 => r=1, ans=2. Centers? All cells: (0,0) -> max distance: to (0,2) = 2 (since Chebyshev: max(|0-0|,|2-0|)=2) => time=3. (0,1) -> distances: to (0,0)=1, to (0,2)=1 => max=1 => time=2. (0,2) -> max=2 => time=3. (1,0) -> to (0,0)=1, to (0,2)=max(1,2)=2? Actually (1,0) to (0,2): |1-0|=1, |0-2|=2 => max=2 => time=3. (1,1) -> to (0,0)=1, to (0,2)=max(1,1)=1 => time=2. (1,2) -> similar. So minimal time=2, matches formula.
Case: grid 3x3, stars at (0,0) and (2,1). row_range=2 => r=1, col_range=1 => r=1, ans=2. Check centers: Need cx,cy such that max(|cx|,|cy|)<=1 and max(|cx-2|,|cy-1|)<=1. Let's find. cx must be in intersection of [ -1,1] and [1,3] => cx=1. cy must be in intersection of [ -1,1] and [0,2] => cy in [0,1]? Actually from first: |cy|<=1 => cy in [-1,1]; from second: |cy-1|<=1 => cy in [0,2]; intersection = [0,1]. So possible centers: (1,0) or (1,1). Both in grid. Compute distances: (1,0) to (0,0):1, to (2,1): max(1,1)=1 => max=1 => time=2. So works.
Case: stars at (0,0), (0,3), (3,0), (3,3) in 4x4 grid. row_range=3, col_range=3 => r=2, ans=3. Check center (1,1): to (0,0)=1, to (0,3)=max(1,2)=2, to (3,0)=max(2,1)=2, to (3,3)=max(2,2)=2 => max=2 => time=3. Good. Center (2,2) also gives max=2. So ans=3.
Case: stars at (0,0) and (2,2) in 3x3. row_range=2, col_range=2 => r=1, ans=2. Check center (1,1): distances 1 and 1 => time=2. Good.
Case: stars at (0,0), (2,0), (0,2) in 3x3. row_range=2, col_range=2 => r=1, ans=2. Center (1,1): distances: to (0,0)=1, to (2,0)=max(1,1)=1, to (0,2)=max(1,1)=1 => time=2. Works.
Case: stars at (0,1), (1,0), (1,2), (2,1) in 3x3 (plus maybe center empty). This is like a plus shape. row_range=2, col_range=2 => r=1, ans=2. Center (1,1): distances all 1 => time=2.
Now, consider a case where the stars are not all within the bounding box of extremes? That's impossible.
Thus formula works.
Now, answer.
But wait, the problem might have a nuance: The perfume spreads from one house to all its adjacent houses in one second, but maybe it only spreads from the house where the perfume was placed? The phrasing "from one house" might be misinterpreted: Could it be that at each second, the perfume spreads from exactly one house (maybe the original) to its adjacent houses? That would be strange; typically it's from all houses that have perfume. But they might have intended that after placement, the perfume spreads from that house to its neighbors, then from those neighbors to their neighbors, etc. That's the usual interpretation.
Given the examples, they say: "Now, it will take Devu 1 secs to put perfume. In the next second, the perfume will spread to all of its adjacent cells, thus making each house haunted." That indicates after the first second of spread, the neighbors are covered. But they didn't mention subsequent spreads. In the example, the spread only needed one step because all houses were within one step. So it's consistent.
Thus we are confident.
Now, coding.
But before final, consider the possibility of large n,m but few stars. Our algorithm still reads entire grid O(n*m) which could be large if n,m up to 10^5 each? That would be huge (10^10) impossible. So n,m likely are moderate. However, we can still optimize by reading line by line and processing each character. Even if n=2000,m=2000, that's 4 million per test, times T=20 => 80 million, which is okay in Python if optimized with sys.stdin and not doing heavy per-character overhead? Possibly okay. But we can also just compute min and max while reading, which is necessary because we need to know positions of stars. Could there be a way without scanning whole grid? No, because we need to know which cells are stars. So we must read all characters.
Thus I think constraints are such that n*m is at most maybe 10^6 per test or similar. Usually CodeChef problems have n,m up to 500 or 1000.
So final solution is as above.
Now, let's also consider using Python's input() with strip, but for large input use sys.stdin.buffer.
We'll implement:
import sys
def solve():
data = sys.stdin.buffer.read().split()
# but careful: The grid lines have no spaces, so each line is a token. So we can parse accordingly.
# First token: T, then for each test case: n, m, then n tokens of length m.
# But using split will split on whitespace, so lines will be separate tokens.
it = iter(data)
T = int(next(it))
out = []
for _ in range(T):
n = int(next(it)); m = int(next(it))
min_r = n; max_r = -1; min_c = m; max_c = -1
count = 0
for i in range(n):
row = next(it).decode() # because data is bytes from buffer, decode to str
# If we want speed, we can keep as bytes and compare to ord('')
# We'll treat as bytes: row_bytes = next(it); then for j in range(m): if row_bytes[j] == ord('')
# But for simplicity decode.
# However, we might have large input, so using bytes is faster.
# I'll implement with bytes.
Actually data is bytes, so row = next(it) is a bytes object. Then we can iterate over it.
We'll do: row = next(it)
for j, ch in enumerate(row):
if ch == 42: # ord('*')
count += 1
if i < min_r: min_r = i
if i > max_r: max_r = i
if j < min_c: min_c = j
if j > max_c: max_c = j
if count == 0:
out.append('0')
else:
r = max( (max_r - min_r + 1)//2, (max_c - min_c + 1)//2 )
out.append(str(r+1))
sys.stdout.write('\n'.join(out))
But careful: (max_r - min_r + 1)//2 is for range? Actually row_range = max_r - min_r. So (row_range + 1)//2. I used (max_r - min_r + 1)//2, which is correct.
Let's test: max_r=2, min_r=0 => (2+1)//2=1. Good.
Now, implement.
Potential bug: if n or m is 0? Not possible.
Now, one more thought: The answer might be simply the maximum of the distances from the center that is the "center of mass" but we have formula.
Now, I'll produce final answer.
But wait, the problem originally might have been from CodeChef "PERFUME" or something, and there might be a nuance: Devu can put perfume in at most one house, but what if there are people in multiple houses? That's fine.
Now, I think we are done.
However, I've seen a known problem "BFS and binary search" but this is simpler. Let me check if there is any tricky test case that breaks our formula.
Consider stars that are at positions such that the bounding box's aspect ratio is not square, but the minimal radius is the half of the larger dimension. That we already did.
Consider if there is only one star, answer=1. Our formula: row_range=0, col_range=0 => r=0 => ans=1. Good.
Now, consider scenario where there are stars only in a single row but far apart. Then r is half the column range, answer = ceil(col_range/2)+1. That seems plausible. But is it always optimal? Could we reduce time by putting perfume not in that row? For example, stars at (0,0) and (0,10). If we put perfume at row 0, col 5, max distance =5 => time=6. If we put at row 1, col 5, distances: to (0,0): max(1,5)=5; to (0,10): max(1,5)=5 => same max=5. So still 6. If we put at row 2, col 5, distances: max(2,5)=5 => still 5. Actually as long as the column difference is 5, row difference adds to max, but the max is max(|dx|,|dy|). Since |dy| is 5 from col difference, any row difference less than or equal to 5 doesn't increase max. So we could put at row 5, col 5, distances: |dx|=5, |dy|=5 => max=5. So still 5. So max distance is at least half the col range. So no improvement.
Now, consider stars at (0,0), (0,5), (5,0). Bounding box: rows 0..5, cols 0..5 -> row_range=5, col_range=5 => r=3 (since ceil(5/2)=3) => answer=4. Check center (2,2)? distances: to (0,0):2,2 =>2; to (0,5):2,3 =>3; to (5,0):3,2 =>3 => max=3. So time=4. Could we do better with center (2,3)? distances: (0,0):2,3 =>3; (0,5):2,2=>2; (5,0):3,3=>3 => max=3. So still 3. Could we get max=2? Then need to cover (0,5) and (5,0) both within Chebyshev distance 2 from center. That would require center within 2 of col 5 => col >=3, and within 2 of row 5 => row >=3, and within 2 of (0,0) => row <=2 and col <=2. These constraints conflict. So r=3 minimal. So correct.
Now, I'm confident.
But wait, there might be a twist: The perfume spreads from one house to all its adjacent houses in one second, but "the cycle continues" might mean that after each second, the perfume spreads from the house that received it last? No, it's typical BFS.
Thus solution.
Now, I'll code.
Potential improvements: We could also compute directly without scanning all characters if we just read lines, but scanning is required.
Now, also note that input format: "For each of next n lines, each line has m characters (without any space)". So lines may have newline, but using split will handle them.
Now, edge case: The line may contain '.' and '*' only. So okay.
Now, code.
We'll use sys.stdin.buffer.read().split() to get tokens. This will treat each line as a token, but also splits on whitespace. However, the grid lines contain no spaces, so they will be separate tokens. That's fine.
But note: The first token is T. Then for each test case, we have n and m as separate tokens, then n lines as tokens. So we can iterate.
We must ensure that the lines are read correctly even if they contain '.' and '*'. No problem.
Implementation:
import sys
def main():
data = sys.stdin.buffer.read().split()
t = int(data[0])
idx = 1
out_lines = []
for _ in range(t):
n = int(data[idx]); m = int(data[idx+1]); idx += 2
min_r = n
max_r = -1
min_c = m
max_c = -1
count = 0
for i in range(n):
row = data[idx]; idx += 1
# row is bytes of length m (maybe with newline stripped? split removes whitespace, so it's exactly the row string)
# but ensure length is m; sometimes if there are spaces? No.
# Iterate over row bytes
for j, ch in enumerate(row):
if ch == 42: # ord('*')
count += 1
if i < min_r: min_r = i
if i > max_r: max_r = i
if j < min_c: min_c = j
if j > max_c: max_c = j
if count == 0:
out_lines.append('0')
else:
r = max( (max_r - min_r + 1) // 2, (max_c - min_c + 1) // 2 )
out_lines.append(str(r + 1))
sys.stdout.write('\n'.join(out_lines))
if name == "main":
main()
But careful: When using data from split(), the row token may be a bytes object containing the row string. For example, row = b'*.' for a row. That's fine. The length will be m.
Now, test with given input:
Input:
2
2 2
.
..
3 4
...
**.
...
Our code: t=2
First test: n=2,m=2; rows: row0=b'*.', row1=b'..'
Processing: row0: j=0 ch=42 -> count=1, min_r=0,max_r=0,min_c=0,max_c=0; j=1 ch=46 ignore. row1: all ignore. count>0 => row_range=0, col_range=0 => r=0 => ans=1. Append '1'. Wait output expects 1? Actually example output first line is 1. Good.
Second test: n=3,m=4; rows: row0=b'...'? Actually input line is "..." so bytes b'...'; row1=b'**.'; row2=b'...'. Process: For row0: j=0 '.'; j=1 '' => count++, min_r=0,max_r=0,min_c=1,max_c=1? Actually min_c initially m=4, so becomes 1, max_c=1. j=2 '.'; j=3 '.'. row1: j=0 '' => count, update: i=1, min_r remains 0? Actually i=1 > max_r so max_r=1; min_c compare j=0 <1 -> min_c=0; max_c compare j=0 -> currently max_c=1, so stays 1? Wait we need to also update for j=1, j=2. For j=1 '' -> j=1 not less than min_c (0) so min_c stays 0; j=1 > max_c? max_c is currently 1? Actually after row0, max_c=1. j=1 not >1, so unchanged. For j=2 '' -> j=2 >1 => max_c becomes 2. j=3 '.' ignore. row2: i=2, j=1 '', update: max_r becomes 2; min_c remains 0; max_c currently 2, j=1 not >2; all good. After processing: min_r=0, max_r=2 => row_range=2; min_c=0, max_c=2 => col_range=2. r = max((2+1)//2=1, (2+1)//2=1)=1; ans=2. Good.
Output lines: ['1','2'] join with newline => "1\n2". matches expected.
Thus correct.
Now, consider a test where there are no stars: e.g., 1 test: 2 2 ....? Actually input: 1\n2 2\n..\n.. . Our code will count=0 => out_lines.append('0').
Now, performance: Reading all tokens at once may be memory heavy if input is huge (nm up to, say, 10^7 characters). That's about 10 MB? Actually each character is one byte, plus overhead of list of bytes objects. But typical constraints allow it. Alternatively, we could use sys.stdin.readline in a loop, but reading all is simpler. However, if nm is large like 10^7, storing all tokens as separate bytes objects plus the list might be okay (10 million tokens? Actually there are n lines per test, T up to 20, total lines maybe 20000 if n=1000 each? Actually worst-case total characters is sum(nm). If each nm=10^6 per test and T=20, that's 20 million characters ~20 MB, which is fine. But the split() will create a list of tokens; the number of tokens is 1 (T) + for each test 2 + n, so total tokens <= 1+20*(2+1000)= about 20021 tokens if n=1000. That's fine. So reading all is acceptable.
But note: if n=10^5 and m=10^5? That would be 10^10 characters, impossible for input. So constraints are modest.
Thus solution is ready.
Now, I will produce final answer.
But before concluding, I want to think if there's any other interpretation: Could Devu put the perfume in a house that is haunted ('.') and then the spread might take different time because the haunted houses maybe are empty? But that doesn't matter.
Also, maybe the perfume spreads to adjacent houses each second but only to houses that are currently not haunted? Actually haunted houses are those with '.' initially; but perfume can spread to any house, regardless of haunting status. So no effect.
Thus answer is correct.
Now, output the solution.
I'll provide the Python code.
But we must note that the problem might be expecting answer as integer, and we should print it per line.
Now, final code:
import sys
def solve():
data = sys.stdin.buffer.read().split()
t = int(data[0])
idx = 1
out = []
for _ in range(t):
n = int(data[idx]); m = int(data[idx+1]); idx += 2
min_r = n
max_r = -1
min_c = m
max_c = -1
cnt = 0
for i in range(n):
row = data[idx]; idx += 1
# if length of row might be less than m due to newline? But split removes whitespace, so it's exactly the row.
# However, there could be the case where row contains only '.' and '', no spaces, so length should be m.
# But to be safe, we can ensure we only consider first m characters, or if row length > m? Not possible.
for j in range(m):
if row[j] == 42: # ''
cnt += 1
if i < min_r: min_r = i
if i > max_r: max_r = i
if j < min_c: min_c = j
if j > max_c: max_c = j
if cnt == 0:
out.append('0')
else:
r = max( (max_r - min_r + 1) // 2, (max_c - min_c + 1) // 2 )
out.append(str(r + 1))
sys.stdout.write('\n'.join(out))
if name == "main":
solve()
But note: In the row loop, we used for j in range(m): row[j] works because row length should be m. But if row length is less (e.g., missing characters due to input error), it may crash. But problem guarantees m characters per line.
Now, final answer.
I'll include explanation in final output.
Now, produce final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
t = int(data[0])
pos = 1
out_lines = []
code
for _ in range(t):
n = int(data[pos]); m = int(data[pos + 1])
pos += 2
min_r, max_r = n, -1
min_c, max_c = m, -1
cnt = 0
for i in range(n):
row = data[pos]
pos += 1
# row is a bytes object of length m
for j in range(m):
if row[j] == 42: # 42 == ord('*')
cnt += 1
if i < min_r: min_r = i
if i > max_r: max_r = i
if j < min_c: min_c = j
if j > max_c: max_c = j
if cnt == 0:
out_lines.append('0')
else:
r = max((max_r - min_r + 1) // 2,
(max_c - min_c + 1) // 2)
out_lines.append(str(r + 1))
sys.stdout.write('\n'.join(out_lines))