We need to understand the problem: We have an n x m table of 0/1. We can perform operations: choose any row i, and cyclically shift left or right by 1 cell. Each such operation counts as 1 move. We want to make some column j consist entirely of 1s. That is, after some number of moves (each move shifts a row left or right cyclically), for some column index j (1-indexed perhaps), every row's value at that column is '1'. We need minimum total moves. If impossible, output -1.
Constraints: n up to 100, m up to 10^4. So we need efficient algorithm: O(n * m) or O(n * m * something small). Brute force over all columns as target: For each column j, we need to compute minimal total moves to align all rows so that at column j they are 1. For each row i, we need to see if we can shift that row to get a 1 at column j. If there is no 1 in that row, it's impossible for any column (since we need all rows to have 1 in that column). Actually for a given target column j, for each row i, we need to move the row so that after some shifts (left/right), the 1 originally at some column k becomes at column j. Since shifts are cyclic, the distance (minimum number of shifts) to bring a specific 1 from its original column to column j is the minimum of left or right cyclic distances. However, there may be multiple 1s in a row; we can choose which 1 to bring to column j, because shifting moves the entire row, and any 1 can end up at column j if we shift appropriately. Since we can shift as many times as we like (with cost = number of shifts), we need to compute for each row i and each target column j, the minimal number of moves (shifts) to get a 1 at column j. That is essentially: For each row i, we need to compute distances to the nearest 1 from each position j (cyclic). Actually, we need minimal shifts to bring some 1 to position j. Since we can shift left or right arbitrarily, the minimal number of shifts is the minimal circular distance (i.e., minimal number of steps) from j to any column that contains a 1 in row i, where a step corresponds to moving the row relative to fixed column. More precisely: Suppose we have a row with columns indexed 0..m-1. If we shift right by 1, elements move to the right: column j gets previous column j-1 (with wrap). So after t shifts right, column j originally contained element from column (j - t mod m). Alternatively, we can think: To bring a 1 that is originally at column k to column j, we can shift right by (j - k) mod m steps, or left by (k - j) mod m steps. The number of shifts required is min((j - k) mod m, (k - j) mod m). But since mod m yields numbers between 0 and m-1, and shift count can't be 0 if we need a 1? Actually if there is already a 1 at j, then distance 0.
Thus for each row i, we can precompute for each column j the minimal distance d[i][j] = min over all columns k where a[i][k]='1' of min( (j - k + m) % m, (k - j + m) % m ). But careful: (j - k + m) % m is the number of right shifts needed to bring k to j? Let's check: If we shift right, the element at column k moves to (k+1) mod m after 1 shift. So after t right shifts, original column k moves to (k+t) mod m. We want (k+t) mod m = j => t ≡ (j - k) mod m. The smallest nonnegative t is (j - k + m) % m. Similarly, left shifts: after t left shifts, original k moves to (k - t) mod m; set equal j => t ≡ (k - j) mod m. So minimal shifts = min( (j - k + m) % m, (k - j + m) % m ). Since both numbers sum to m (unless they are equal when m even? Actually if m is even, and distances? Let's see: For any two distinct positions, (j - k) mod m and (k - j) mod m are complementary: they sum to m (if not 0). Because (j - k) mod m = d, then (k - j) mod m = m-d (if d != 0). So min(d, m-d). So indeed the minimal circular distance.
Therefore, for each row i, we need d[i][j] = minimal circular distance to a 1.
Then for each candidate column j, total moves needed = sum_{i=1..n} d[i][j]. We take min over j. If any row i has no 1 at all, then for all j, d[i][j] would be undefined? Actually if a row has no 1, it's impossible to get a column of all 1s because that row would always have 0 at any column regardless of shifts (since shifting doesn't change the set of values, just permutes them cyclically). So if any row has no 1, answer is -1. That's a necessary condition.
Now the challenge: compute d[i][j] efficiently for n up to 100, m up to 10^4 => 1e6 entries per row? Actually nm up to 10010000 = 1,000,000. That's okay. For each row i, we can compute distances to nearest 1 to left and right using two passes, like computing minimal distance to next '1' in a circular array.
But careful: Because the row is circular, we need for each index j the minimal distance to any 1. One typical approach: For each row, we can mark positions of 1s. Then for each column j, we compute distances to nearest 1 on left and right along the circle, and take min distance. Since m up to 1e4, we could also for each row do O(m * #ones) but #ones could be up to m. That would be O(m^2) per row worst-case, which is 1e8 per row? Actually n=100, m=10000 => 1e8 total if we do O(m^2) per row? That's too high (1e8 maybe borderline but with constant factor may be okay in Python? Possibly not, we want efficient O(m) per row).
So we should do linear-time per row. Approach: For each row i, we can first find all indices where a[i][j] = '1'. Then for each j, we compute distance to the nearest 1 in the cyclic sense. Since the row is circular, we can duplicate the array to handle wrap-around, but we need min distance which is min between distance to next 1 on right and left.
Simplify: Because distance is min( distance to nearest 1 going forward (right) or backward (left) ), we can compute for each position the distance to the next 1 to the right (circularly) and to the left. Then take min of those distances.
A common technique: Do a pass from left to right computing distance to the previous 1 (going leftwards), but that gives distance to left neighbor only. Similarly, we can do a pass from right to left for right neighbor. Then for each position, we can compute min of left distance and right distance, but careful because due to circularity, the left neighbor might be across the boundary. We can handle by doing two passes on a doubled array of length 2m, but we can also compute circularly by considering that after we have computed next_1_to_right (in the sense of moving forward with wrap) as the distance to the nearest 1 in the forward direction (including wrap) then we can combine.
Let's define positions 0..m-1. For each position j, we want:
- left distance: minimal t such that there is a 1 at position (j - t) mod m (i.e., moving left t steps). That is essentially the distance to the nearest 1 when moving backwards.
- right distance: minimal t such that there is a 1 at (j + t) mod m.
Then d[j] = min(left_dist, right_dist).
We can compute right distance by scanning: first find positions of 1s. Then for each position, compute distance to the next 1 to the right (without wrap). That's straightforward by scanning from right to left: keep track of last index of a 1 seen; for each j, the next 1 to the right (within the array, not wrap) is at that last index; distance = last - j if last>=j, else infinity. After that, we need to account for wrap: the next 1 might be from the left side if there is no 1 to the right. To get the circular right distance, we can compute the distance to the nearest 1 in the circular forward direction. Another way: After we have distances to the next 1 to the right (non-wrap) and to the previous 1 to the left (non-wrap), we can compute the wrap distance: for the right distance, if there is a 1 to the right within the array, that's the forward distance. Otherwise, the nearest forward 1 would be the first 1 from the start of the array (wrap), and distance = (m - j) + (index_of_first_1). Similarly for left distance: if there is a 1 to the left, distance = j - prev; else distance = j + (m - last_1_index). So we can compute using two passes to get prev and next arrays.
Let's do that:
For each row:
- Create array next_one_right of length m, initialized to some large value.
- Traverse from right to left: last = -1; for j from m-1 down to 0:
if a[i][j]=='1': last = j
next_one_right[j] = last // store index, could be -1 if none to right
- Then traverse from left to right: prev = -1; for j from 0 to m-1:
if a[i][j]=='1': prev = j
left_one_index = prev // maybe store
But we need distances, not indices, after we have both.
For each j, compute:
- If next_one_right[j] != -1: right_dist = next_one_right[j] - j
else: right_dist = (m - j) + first_one_index // first_one_index is the index of the first 1 from left (the smallest index with a 1) (if exists, we know row has at least one 1 because otherwise answer -1 overall)
- If prev_one_left[j] (i.e., left index) != -1: left_dist = j - left_index
else: left_dist = j + (m - last_one_index) // last_one_index is the index of the last 1 (largest index) (if exists)
But careful: In the second pass we can store left_one_index similarly: left_index[j] = prev (closest 1 on left, non-wrap). Then after passes we also need first_one_index and last_one_index.
Alternatively, we can compute distances more directly by scanning and using the fact that the minimal distance to a 1 is the minimum of (j - left) and (right - j) for the non-wrap case, but we also need to consider wrap distances: (j + m - right) if right is to the left? Actually consider that if we have left index L (<= j) and right index R (>= j) within array, then distances are j-L and R-j, min works. If left is absent (i.e., no 1 on left), then we need wrap to left: distance = (j) + (m - last_one_index)? Actually the nearest 1 in left direction when no 1 to left means we need to go leftwards wrapping around to the rightmost 1. That distance = j - (-1)?? Let's think: Starting at position j, if we move left (decreasing index) we eventually hit 0 then wrap to m-1, m-2,... until we hit a 1. The number of left steps needed = j - L? Actually if there is no 1 with index <= j, then the nearest 1 in the left direction is the rightmost 1 in the array (largest index). To go left from j, we go to j-1,...0, then to m-1,... down to that rightmost 1. Steps = j + 1 + (m-1 - last_one_index)? Actually we need to compute the number of left shifts to bring that 1 to column j. Alternatively, distance in terms of circular left distance: from j to some index k (with k > j maybe) going leftwards (i.e., decreasing index with wrap) is: if we go left t steps, we reach (j - t) mod m. We need (j - t) mod m = k. So t = (j - k) mod m. Since k > j, (j - k) mod m = m - (k - j). That's the same as the forward distance from k to j? Actually careful: If we have a 1 at index k > j, then left distance from j to k is (j - k) mod m = m - (k - j). That is the distance going leftwards, i.e., we go left from j to 0 and wrap around to m-1 down to k. That number is m - (k - j). Similarly, if k < j, left distance = j - k. So we can compute left distance using the left neighbor (closest 1 with index <= j) if exists; otherwise, use the rightmost 1 (which is > j? Actually if there is no 1 <= j, then all ones are > j. Then the nearest left distance would be the minimal over those k > j of m - (k - j) = m - (k - j). That is minimized when (k - j) is minimal? Actually m - (k - j) is larger when k-j is larger, so we want k as small as possible > j? Since k > j, the minimal left distance would be with the smallest k > j, because that gives the smallest (k-j) and thus largest m - (k-j)? Wait we need the smallest left distance. For k > j, left distance = m - (k - j). Since m is constant, this decreases as (k - j) increases? Let's check: if k = j+1, left distance = m - 1; if k = j+2, left distance = m - 2; so actually left distance is smaller when (k-j) is larger. That makes sense because moving left to reach a far away index across the wrap might be shorter? Actually consider m=10, j=5. If there is a 1 at k=6, left distance = (5-6) mod 10 = 9, which is large. If there is a 1 at k=9, left distance = (5-9) mod 10 = 6, which is smaller. If there is a 1 at k=4 (<=j), left distance = 1 (if k=4). So indeed, if there is a 1 on left (≤j), that gives a small distance. If not, then the left distance is determined by the largest index k (since it gives smallest m-(k-j)). Actually we want minimal left distance, so among k > j, left distance = m - (k - j). This is minimized when (k - j) is maximized, i.e., when k is as large as possible (closest to m-1). So the best left distance when no 1 to left is with the rightmost 1 (largest index). Similarly, for right distance (moving right), if no 1 to the right (i.e., all 1s have index ≤ j), then the right distance is determined by the leftmost 1 (smallest index) via wrap: right distance = (m - j) + leftmost_index. So we need first and last 1 indices.
But perhaps we can avoid dealing with wrap separately by using a method where we replicate the row twice and compute distances in a linear array. Since m up to 10^4, 2m = 20k, still fine. For each row, we could create an array of length 2m, where we copy the row twice. Then for each position in the original segment (0..m-1), we compute the distance to the nearest 1 in the duplicated array. However, we must consider that the distance might be more than m/2? Actually the minimal circular distance never exceeds floor(m/2). But using duplication, we can compute the nearest 1 to the left and right within a window of length m? Alternatively, we can compute for each position j the minimal distance to any 1 in the circular sense by scanning the duplicated array from the center.
Simpler: For each row, we can precompute an array dist_to_one of size m with large values. First, set dist = INF. Then we can do a forward scan to compute distances to the next 1 to the right (non-wrap) as described, but then we can also compute the wrap distances by considering the next 1 to the right from the start of the array for positions near the end. But we need to be careful about the left distance as well.
Given that we have at most 100 rows and m=10000, a straightforward O(m * #ones) could be borderline but possibly acceptable if #ones average small? But worst-case #ones = m=10000, then O(m^2)=1e8 per row -> 1e10 overall, impossible. So we need linear.
We can compute for each row the distances d[i][j] using BFS-like approach on a circular array? Actually because distance is just the minimal number of shifts, which is like distance on a circle. We can treat the row as a binary string and compute for each index the distance to the nearest '1' on the circle. This is similar to "circular distance to nearest 1". We can compute using two passes with wrap-around as described. Let's formalize:
Let positions 0..m-1. Let left_dist[j] = distance to the closest 1 when moving left (i.e., decreasing index, with wrap). This can be computed by scanning left to right? Actually we can compute the distance to the nearest 1 on the left (non-wrap) easily: prev_one = -1; for j in 0..m-1: if a[j]=='1': prev_one = j; left_nonwrap_dist[j] = j - prev_one if prev_one != -1 else INF.
Similarly, right_nonwrap: next_one = -1; for j from m-1 down to 0: if a[j]=='1': next_one = j; right_nonwrap_dist[j] = next_one - j if next_one != -1 else INF.
Now we need to consider wrap contributions:
- For left distance (i.e., moving leftwards) the actual circular left distance is: if there is a 1 on left (prev_one != -1) then left_dist = j - prev_one; else (no 1 at all? impossible because row has at least one 1), then we need to wrap: the nearest leftwards is from the rightmost 1 (largest index). The distance would be: j + (m - last_one). Because from j, moving left: go to 0, then to m-1, then down to last_one. Steps: j steps to reach index 0 (if we move left from j to 0, that's j steps? Actually moving left one step decreases index by 1. Starting at j, after j steps we reach 0? Let's calculate: If j=2, moving left: step1 -> 1, step2 -> 0. So j steps to reach 0. Then from 0, to get to last_one (which is some index L), we need to wrap: from 0 to L moving left? Actually after reaching 0, the next left step goes to m-1. To go from 0 to L via left direction: we go 0 -> m-1 (1 step), then continue decreasing: m-1 -> m-2 -> ... -> L. That number of steps is (m-1 - L) + 1? Let's compute precisely: Starting at j, we want to move left until we hit index L (the rightmost 1). The path: left from j to 0: j steps (since each step decrements by 1). At 0, the next left step goes to m-1. Then we continue left until we hit L. The number of steps from 0 to L via left: To reach L from 0 by going left, we go from 0 to m-1 (1 step), then from m-1 down to L: (m-1 - L) steps. So total steps = j + 1 + (m-1 - L) = j + (m - L). But is that correct? Let's test: m=5, indices 0..4. Suppose L=4 (rightmost 1). j=0. Then left distance to that 1 should be? If we move left from 0: one left step goes to 4 (since wrap). So distance = 1. Our formula gives j + (m - L) = 0 + (5-4)=1. Good. Suppose L=3, j=0: left step: 0->4 (1), then 4->3 (1) = 2. Formula: 0+(5-3)=2. Good. Suppose L=2, j=1: we have a 1 at 2. Actually j=1, left distance to index 2? Wait left direction from 1: decreasing index: 1->0 (1 step), 0->4 (2), 4->3 (3), 3->2 (4). So distance =4. But note there is also a right distance perhaps smaller. But for left distance only, if we want to reach 2 (which is > j) by left moves, it takes 4 steps. Formula: j + (m - L) = 1 + (5-2)=4. Good. But is that the minimal left distance? Could there be a 1 at a smaller index? But we assumed no 1 to left (i.e., no 1 with index <= j). So L is the largest index (since all ones are > j). Actually if there is no 1 <= j, then all ones are > j. Among those, the left distance to a 1 at index k is (j - k) mod m = m - (k - j). Since k - j is between 1 and m-1. This distance is minimized when (k - j) is maximized, i.e., k as large as possible, i.e., last_one (largest index). So indeed the minimal left distance is j + (m - last_one). That matches our derivation.
Similarly, for right distance (moving rightwards) if there is no 1 to the right (next_one == -1), then the minimal right distance is (m - j) + first_one, where first_one is the smallest index with a 1.
Therefore algorithm for each row:
-
If the row has no '1', then overall answer = -1. (We can check early).
-
Find list of indices with '1's. Also compute first_one = min(indices), last_one = max(indices). (If there is only one, both same).
-
Initialize arrays left_dist_nonwrap = [inf]*m, right_dist_nonwrap = [inf]*m.
Compute left neighbor index: prev = -1
for j from 0 to m-1:
if row[j] == '1': prev = j
left_idx[j] = prev # may be -1
Actually we need distance, but we can compute later.
Compute right neighbor index: nxt = -1
for j from m-1 down to 0:
if row[j] == '1': nxt = j
right_idx[j] = nxt
-
For each column j:
# compute left distance
if left_idx[j] != -1:
left_dist = j - left_idx[j]
else:
left_dist = j + (m - last_one) # because no 1 on left
# compute right distance
if right_idx[j] != -1:
right_dist = right_idx[j] - j
else:
right_dist = (m - j) + first_one
d[i][j] = min(left_dist, right_dist)
But we need to verify correctness for cases where there is a 1 on both sides. For example row: ... at j, there is both left and right 1s. The above gives left_dist = j - left_idx, right_dist = right_idx - j. That's correct for non-wrap distances. But what about the wrap contributions? Could it be that the minimal distance is actually via wrap rather than the immediate left/right? For instance, suppose left_idx is far, right_idx is far, but wrap to the other side yields a smaller distance. For example: m=10, ones at indices 0 and 9. For j=5: left_idx = 0? Actually left_idx would be 0 (since 0 <=5). Right_idx = 9. left_dist = 5-0=5, right_dist = 9-5=4. But the actual minimal circular distance is min(5,4, ?) but also possible via left to 9? left distance to 9 is? That would be (5-9) mod 10 = 6, not smaller. So not an issue. The minimal is indeed min(j-left_idx, right_idx-j) because those are the distances to the nearest 1 in the two directions along the circle; any wrap path corresponds to distance (j + m - some_k) or (m - j + some_k), but those are essentially the distances to the ones that are not the nearest on the linear order? Actually for a given j, the set of distances to all ones is either j - k for k <= j, and m - (j - k) for k > j? Wait, careful: For each one at index k, the circular distance is min(|j-k|, m - |j-k|). Since |j-k| is the direct difference without wrap. But the min function ensures that if the direct difference is > m/2, then the wrap distance m - direct difference might be smaller. In our approach, by considering left_dist = j - left_idx (if left_idx exists) and right_dist = right_idx - j, we are only considering the immediate neighbors (closest on left and right in terms of index, not necessarily closest in circular distance). However, is it guaranteed that the minimal circular distance is given by min( j - left_nearest, right_nearest - j, possibly also m - (j - left_nearest), m - (right_nearest - j) )? Actually for any one at index k <= j, the circular distance = min( j - k, m - (j - k) ). Since j - k is the direct difference. For the nearest left neighbor, j - k is the smallest among all k <= j. So the min among those for left side is min over k<=j of min(j-k, m-(j-k)). The smallest possible j-k is from left_nearest, but it could be that m-(j-k) is smaller for some further left neighbor? For a fixed j, as k decreases (further left), j-k increases, so m-(j-k) decreases. So the minimum over k<=j of min(j-k, m-(j-k)) is either from the nearest left neighbor if j - left_nearest <= m/2, or possibly from some further left if j - left_nearest > m/2, then m-(j - left_nearest) might be >? Actually we need to find the k that minimizes f(k) = min(|j-k|, m-|j-k|). For k <= j, |j-k| = j-k. The function f(k) = min(j-k, m-(j-k)). As k decreases from j to 0, j-k increases from 0 to j. So min(j-k, m-(j-k)) initially equals j-k (since j-k <= m/2 for small differences). Once j-k exceeds m/2, then min becomes m-(j-k), which decreases as j-k increases further. So the minimum over k <= j could occur at either the point where j-k is as small as possible (nearest left) or where m-(j-k) is as small as possible, which occurs when j-k is as large as possible (farthest left). So the minimal among left side might be from the farthest left (i.e., the leftmost index) if the nearest left is far enough (> m/2) and the wrap distance from the leftmost could be smaller. But note: The farthest left is leftmost 1 (first_one). For k = first_one, j - k is large, but m-(j-k) could be small if (j-k) is close to m. However, is it possible that first_one yields a smaller circular distance than the nearest left neighbor? Example: m=10, ones at indices 0 and 6. Consider j=3. Left neighbor: there is no 1 with index <=3? Actually ones: 0 and 6. left_idx[3] = 0 (since 0 <=3), right_idx[3]=6. left_dist = 3-0=3. right_dist=6-3=3. The circular distance to 0 is min(3,7)=3; to 6 is min(3,7)=3. So min=3. Is there a case where left_idx exists but the minimal circular distance is not min(left_dist, right_dist)? Consider ones at indices 0 and 9. m=10. For j=5: left_idx=0, right_idx=9. left_dist=5, right_dist=4 -> min=4. But circular distance to 0 is min(5,5)=5; to 9 is min(4,6)=4; min=4. OK. Now consider ones at indices 0 and 4. m=10, j=9. left_idx? Indexes <=9: both 0 and 4. The nearest left is 4? Actually left_idx[9] should be the rightmost index with a 1 that is <=9. That is 4 (if 4<9) but also 0, but the rightmost among <=9 is 4. So left_idx=4, left_dist=9-4=5. right_idx? there is no index >=9 with a 1, so right_idx = -1. Then our algorithm would compute left_dist=5, right_dist = (m - j) + first_one = (10-9)+0=1. So d=1. Indeed, the minimal circular distance is 1 (from 9 to 0 via right shift? Actually shift right? Let's compute: to bring 0 to 9, right shift by 9? Wait we need a 1 at column 9. There is a 1 at 0. The distance from 0 to 9: min(9, 1) = 1 (since 10-9=1). So indeed min distance is 1, which is captured by the wrap right distance. But our left_dist gave 5, not minimal. However we also have right_dist computed via wrap, so min(5,1)=1. So it works because we considered wrap when right_idx is -1. But note that left_idx existed but the minimal came from wrap (right distance via wrap) because the nearest right neighbor (in linear sense) didn't exist, but we considered wrap. So the algorithm accounts for wrap distances for both directions when the immediate neighbor in that direction is missing. However, could there be a scenario where both left_idx and right_idx exist, but the minimal circular distance is not simply min(left_dist, right_dist) because a wrap distance via the other side might be smaller than both? For example, consider ones at indices 2 and 8 in m=10. For j=5: left_idx=2, left_dist=3; right_idx=8, right_dist=3; min=3. But is there a wrap distance smaller? Distance to 2 via left direction: left_dist already 3. Distance to 8 via right: 3. Distance to 2 via wrap? That would be m - (5-2)=10-3=7, larger. Distance to 8 via wrap? m - (8-5)=10-3=7. So min=3. No better.
But consider ones at indices 0 and 6, j=9 we already did: left_idx=6, left_dist=3? Actually j=9, left_idx? indices <=9: 0 and 6, the rightmost is 6, so left_dist=9-6=3. right_idx? none >=9, so right_dist = (10-9)+0=1. min=1. That case had right_idx missing.
Consider ones at indices 0 and 7, j=4: left_idx=0? Actually indices <=4: 0 only, so left_dist=4. right_idx=7, right_dist=3. So min=3. But what about wrap left distance to 7? That would be (4-7) mod10 = 7? Actually left distance to 7 = (4-7) mod10 = 7 (since 4-7 negative -> 10-3=7). So not smaller. Good.
Now consider a case where both left and right neighbors exist, but the nearest circular distance is via wrap to a far neighbor that is not immediate. For that to happen, the immediate left neighbor might be at distance > m/2, and the immediate right neighbor also > m/2, but then the circular distance to either would be computed as min(d, m-d). If d > m/2, then min(d, m-d) = m-d. So if left_dist > m/2, then the circular distance to that left neighbor is m - left_dist. But left_dist = j - left_idx. That could be > m/2 if left_idx is far left. However, note that if left_dist > m/2, then the wrap distance to that left neighbor is m - left_dist, which is less than left_dist. But is that captured by our algorithm? Because we only compute left_dist as j - left_idx, and then we take min(left_dist, right_dist). But we didn't consider m - left_dist. However, note that m - left_dist is actually the right distance to that same neighbor? Wait, if left_dist > m/2, then the circular distance to that left neighbor is m - left_dist. But how could we achieve that distance via shifts? The minimal shifts to bring that left neighbor to column j would be min(left_dist, m-left_dist). Since left_dist > m/2, the minimal is m-left_dist. That minimal could be achieved by shifting the row in the opposite direction (right shifts) to bring that left neighbor to column j. In terms of our left/right classification, that corresponds to moving rightwards from that left neighbor to j, which is a right distance from j to that neighbor? Let's think: For a 1 at index k = left_idx, we have two possible shift counts: left_dist = (j - k) mod m, and right_dist = (k - j) mod m = m - (j - k). So right_dist = m - left_dist. Since we are considering the minimal of these two, the actual distance to that 1 is min(left_dist, right_dist). Our algorithm currently only considers distances to the immediate left neighbor as left_dist, and distances to the immediate right neighbor as right_dist, and then takes min(left_dist, right_dist) but not the alternative distance to the same neighbor. However, the min for that particular neighbor is min(left_dist, m-left_dist). If left_dist > m/2, then the minimal distance for that neighbor is m-left_dist. But does our algorithm account for m-left_dist? Possibly, it could be captured by the distance to the right neighbor? Because m-left_dist is the number of right shifts needed to bring that left neighbor to column j. But that is essentially the distance from j to that left neighbor going rightwards (wrap). That is not the same as the distance to the immediate right neighbor (which is a different 1). However, it's possible that m-left_dist is smaller than both left_dist and the right neighbor's distances. In that case, our current min(left_dist, right_dist) may miss it because we didn't consider the wrap distance for the left neighbor. But could such a scenario occur when both left and right neighbors exist? Let's construct an example.
We have row with 1s at positions: say m=10. We have a left neighbor at k1 (<= j) and a right neighbor at k2 (>= j). The distances are d1 = j - k1, d2 = k2 - j. If d1 > m/2, then j - k1 > 5. But since k1 <= j, j - k1 can be at most j. For d1 > 5, j must be >5. But then what about k2? Since k2 >= j, d2 = k2 - j >=0. Could it be that d2 is also > m/2? That would require k2 - j >5, but since k2 <= m-1, j could be small. For both d1 and d2 >5 simultaneously, we would need j such that j - k1 >5 and k2 - j >5. That means there is a gap of more than 5 on both sides. But note that the total circle length is m=10. If we have a left neighbor and a right neighbor, the sum of distances (j - k1) + (k2 - j) = k2 - k1. For both to be >5, then k2 - k1 >10, which is impossible since max difference is 9 (if k1=0, k2=9, then j somewhere? Suppose k1=0, k2=9. Then j - k1 = j, k2 - j = 9 - j. For both >5, we need j>5 and 9-j>5 => j<4. Contradiction. So they can't both be >5 simultaneously when there are two distinct neighbors on both sides. If there is only one 1, then we handle wrap distances via the case where one side is missing. So it seems that when both left_idx and right_idx exist, at least one of d1, d2 is ≤ floor(m/2). Because the two distances sum to k2 - k1 (if they are the immediate neighbors, the ones that are closest on each side, they are adjacent in the sorted list of 1 positions). Actually, suppose sorted positions of ones: ... p_i, p_{i+1}, ... For a given j, the left neighbor is the largest p ≤ j, right neighbor is the smallest p ≥ j. Then d1 = j - p_i, d2 = p_{i+1} - j. Note that p_{i+1} - p_i = d1 + d2. Since p_{i+1} - p_i ≤ m? Actually could be large if there are only two ones far apart. The maximum gap could be up to m-1. But even if the gap is large, d1 and d2 sum to that gap. Could both d1 and d2 be > m/2? That would require d1 + d2 > m, so gap > m. But maximum gap is m-1? Actually if there are only two ones, the gap between them in the circular sense might be the smaller arc? But here p_i and p_{i+1} are adjacent in sorted order, not necessarily adjacent around the circle; there could be a wrap gap between the last and first ones. But when we consider left and right neighbors in linear order, the right neighbor might be the first one if j is near end? Actually our definition of left_idx and right_idx using linear indexing with wrap considered separately might produce cases where both exist but the gap across wrap is not considered. Let's define: We compute left_idx as the nearest 1 with index ≤ j (or -1). right_idx as the nearest 1 with index ≥ j (or -1). This covers all ones in linear sense. But what about the wrap gap between the last 1 (max index) and the first 1 (min index)? In the linear view, if j is near the end, right_idx may be -1 if no 1 ≥ j, and we handle wrap. But if there is a 1 at a high index (e.g., index 9) and also at index 0, then for j=8: left_idx would be? There is a 1 at index 0? 0 ≤8, so left_idx would be the rightmost index ≤8. If there is also 9, but 9 is >8, so left_idx could be 0 or maybe there is a 1 at 5 etc. But suppose only ones at 0 and 9. For j=8: left_idx = 0 (since 0 ≤8 and it's the only one ≤8). right_idx = 9 (since 9≥8). So both exist. Then d1 = 8-0=8, d2=9-8=1. d1=8 > m/2=5, d2=1 ≤5. min(d1,d2)=1, and the circular distance to the left neighbor (0) is min(8,2)=2? Wait m=10, min(8,2)=2. That's larger than 1. So min is 1 from right neighbor. So our min(d1,d2) yields 1, correct. However, the circular distance to left neighbor is 2, not captured by d1 but min(d1,d2) is already smaller. So not a problem.
But consider scenario where there are three ones: ones at indices 0, 4, 7. m=10. For j=9: left_idx = 7 (largest ≤9), d1=2. right_idx? none ≥9? Actually 0 is not ≥9, so right_idx = -1. So we compute right_dist via wrap: (10-9)+first_one=1+0=1. min=1. Works.
What about j=5: left_idx = 4, d1=1; right_idx=7, d2=2; min=1. Good.
Now try to find a case where both left_idx and right_idx exist, but the minimal circular distance to some 1 is neither d1 nor d2, but a wrap distance to a 1 that is not the immediate neighbors? That would be a 1 that is not the closest on left or right in linear sense. However, if that 1 gives a smaller circular distance, then its circular distance would be min(|j-k|, m-|j-k|). Since it is not the immediate neighbor, its |j-k| is larger than either d1 or d2? Actually if there is a 1 at k such that k < left_idx (further left), then |j-k| = j-k > d1. The circular distance could be m - (j-k). Could that be smaller than d1? For that to happen, we need m - (j-k) < d1, i.e., j-k > m - d1. Since j-k > d1 (because k < left_idx => k ≤ left_idx-? Actually left_idx is the largest ≤ j, so any k < left_idx has k ≤ left_idx - something, so j-k >= j-(left_idx-1) = d1+1. So j-k is at least d1+1. Then m - (j-k) ≤ m - (d1+1). For this to be < d1, we need m - d1 -1 < d1 => m < 2d1+1. If d1 > (m-1)/2, then it's possible. For example, m=10, d1=6 => m - d1 -1 =3, which is <6. So if left_idx gives d1=6, then there might be a further left 1 (say k smaller) with j-k=9 (if left_idx=4, j=10? Actually j must be between indices, but with m=10, indices 0..9). Let's try to craft an example: m=10, ones at indices 0, 1, and 9? But left_idx would be the largest ≤ j. We want left_idx such that d1 >5. Suppose we have ones at indices 0 and 3. For j=9: left_idx = 3? Actually 3 ≤9, yes. So left_idx=3, d1=6. Right_idx? none ≥9? There is 0? 0 is not ≥9, so right_idx = -1. So this falls into case where right_idx missing, and we compute wrap right distance. That wrap distance might be better. But then both left_idx and right_idx don't both exist; right_idx missing.
To have both exist, we need at least one 1 with index ≥ j. So for j near the end, we need a 1 with high index. For d1 to be >5, left_idx must be far left, like index 3 when j=9 gives d1=6. To also have a right_idx, we need a 1 at index ≥9, say index 9. Then left_idx = 3, d1=6; right_idx = 9, d2=0? Actually if there is a 1 at 9, then for j=9, d2=0, min=0. So not interesting. For j=8: left_idx = 3, d1=5; right_idx = 9, d2=1; d1=5 (≤5), d2=1. min=1. If left_idx = 3, j=8 gives d1=5, okay. d1 not >5. For d1>5 we need j - left_idx >5. For j=8, left_idx <=2. Suppose left_idx=2, j=8 => d1=6. To have a right_idx, need an index >=8, say 9. Then d2=1. Then min=1, but d1=6 >5. The circular distance to left_idx=2 is min(6,4)=4. That is 4, which is greater than 1. So min is still 1. So we are fine.
What about a scenario where both d1 and d2 are > m/2? As argued earlier, it's impossible if we have both neighbors defined in the linear sense because d1 + d2 = (right_idx - left_idx) which is ≤ m-1? Actually if left_idx and right_idx are the immediate neighbors in sorted order (not wrap), then right_idx > left_idx. Then d1 + d2 = right_idx - left_idx. For both > m/2, we need right_idx - left_idx > m. Since maximum possible difference is m-1 (if left_idx=0, right_idx=m-1, difference = m-1). For both > m/2, we need sum > m, so difference > m. But max is m-1, so impossible. However, what if the immediate neighbors are not left_idx and right_idx because we are using linear indexing with -1 for missing? Actually when both left_idx and right_idx exist, it implies there is at least one 1 ≤ j and at least one ≥ j. Then the smallest right_idx is the first 1 to the right, and the largest left_idx is the last 1 to the left. Their difference is right_idx - left_idx, which is at most m-1 (since indices are within 0..m-1). So indeed d1+d2 = right_idx - left_idx ≤ m-1. For both d1 and d2 to exceed m/2, we would need right_idx - left_idx > m, impossible. Thus at least one of d1,d2 is ≤ floor((right_idx - left_idx)/2) ≤ floor((m-1)/2). So min(d1,d2) ≤ m/2. And for any other 1 (not immediate neighbors), its distance to j in terms of circular distance will be at least min(d1,d2) because the immediate neighbors already provide the smallest direct distances. But could a farther 1 provide a smaller wrap distance than min(d1,d2)? Let's analyze: Suppose d1 ≤ d2 and d1 ≤ m/2. Then min(d1,d2)=d1. For any other 1 at k, we consider its circular distance f(k) = min(|j-k|, m-|j-k|). Since |j-k| ≥ d1 (because d1 is the minimum absolute difference to any 1? Actually d1 is the absolute difference to the left neighbor? Not exactly: The minimum absolute difference among all 1s is min(d1, d2) if we consider linear absolute difference. Because any k < left_idx will have |j-k| = j-k > j-left_idx = d1. Any k > right_idx will have |j-k| = k-j > right_idx - j = d2. So the smallest absolute difference is min(d1,d2). So for any k, |j-k| ≥ min(d1,d2). Then f(k) = min(|j-k|, m-|j-k|) ≥ min( min(d1,d2), m - |j-k| ). Since |j-k| ≥ min(d1,d2), we have m-|j-k| ≤ m - min(d1,d2). That could be smaller than min(d1,d2) if min(d1,d2) > m/2. But we already have min(d1,d2) ≤ m/2 in the case both neighbors exist. So min(d1,d2) ≤ m/2 implies that m - min(d1,d2) ≥ m/2 ≥ min(d1,d2). So the wrap distance to any other 1 would be at least? Actually for a k with |j-k| > m/2, f(k) = m - |j-k| < m/2. But could this be less than min(d1,d2)? Suppose min(d1,d2)=3, and there is a k with |j-k|=9 in m=10, then f(k)=1, which is less than 3. But if |j-k|=9, then absolute difference is 9, which is > min(d1,d2)=3. But can such a k exist while both neighbors exist? If m=10, min(d1,d2)=3, that implies there is a 1 within 3 steps. For there to be a k with |j-k|=9, that means there is a 1 near the opposite side. But then that k is either left of all left neighbors or right of all right neighbors. For instance, if left_idx is at 3, right_idx at 7, j=5, d1=2, d2=2, min=2. Could there be a 1 at index 0? That would be left of left_idx. Then |j-k| = 5, which is >2. f(k)=min(5,5)=5, not less. For |j-k|=9, j=5, k would be either -4 (impossible) or 14 (impossible). Actually |j-k|=9 with m=10 is possible if k= (j+9) mod 10? But that would be 4? Wait 5+9=14 mod10=4, so k=4 gives |5-4|=1, not 9. The absolute difference mod? Actually absolute difference is at most 9, but to have 9, one would be 0 and the other 9. For j=5, the absolute difference to 0 is 5, to 9 is 4. So max is 5. So the maximum absolute difference is 5 (since m=10, maximum is 5? Actually max |j-k| is up to 9, but for a given j, the max is max(j, m-1-j). So for j=5, max is 5. So you can't have |j-k|=9 for m=10 if j=5. More generally, for any j, |j-k| ≤ max(j, m-1-j) ≤ m-1. But the wrap distance m - |j-k| could be small if |j-k| is close to m. That requires |j-k| > m/2. For that to happen, the 1 must be on the "far side" of the circle. But if we have both a left and right neighbor, the far side might be the other side across the circle. However, could the absolute difference to that far 1 exceed m/2? Yes, if the 1 is on the opposite side from j. For example, m=10, j=2. Suppose we have ones at indices 0, 5, 9. Sorted: 0,5,9. For j=2, left_idx = 0 (d1=2), right_idx = 5 (d2=3). min(d1,d2)=2. Now consider the 1 at index 9. |2-9|=7, > m/2 (5). So f(9) = min(7,3)=3, which is >2. So not smaller. What about a scenario where min(d1,d2) is relatively large, say 4, and there is a 1 on the opposite side giving wrap distance 2? For min(d1,d2)=4, we need d1=4 and d2 maybe something else. For d1=4, j - left_idx =4, so left_idx = j-4. For there to be a far 1 with |j-k| > m/2 and m-|j-k| <4, we need m-|j-k| ≤3, i.e., |j-k| ≥ m-3. Since |j-k| ≤ max(j, m-1-j). For this to be possible, we need max(j, m-1-j) ≥ m-3, i.e., j near one end: either j ≥ m-3 or j ≤ 2. Then consider if j is near end, say j = m-1 (last index). Then left_idx exists (some 1 ≤ m-1), and right_idx might be missing (since no index ≥ m-1 except maybe m-1 itself). But if there is a 1 at m-1, then d=0. If not, then right_idx is missing, we use wrap. In that case, our algorithm would compute right_dist via wrap and potentially get a small number. So again the case where both neighbors exist doesn't happen when j is extreme because right_idx may be missing. Actually for j=m-1, if there is a 1 at index m-1, then right_idx = m-1, so both exist (left_idx could be something else). Then d2=0, so min=0. If there is no 1 at m-1, then right_idx is -1 (since no index ≥ m-1 with a 1, except possibly if we consider wrap? No, we treat right_idx as the first index ≥ j, so if no such index, it's -1). So for j=m-1, right_idx is -1 unless there is a 1 exactly at m-1. So in many cases at the ends, one side is missing, which we handle by wrap. So the only scenario where both sides exist and the minimal distance could be via a wrap of a far 1 is when j is not at the ends and the immediate neighbors are both relatively close? Actually if both sides exist, at least one neighbor is within distance ≤ m/2, as argued. Therefore, the minimal circular distance is indeed min(d1, d2, maybe wrap distances?). But could the wrap distance to the far side (i.e., the distance to the 1 on the other side of the circle) be less than min(d1, d2)? Suppose d1 = 5, d2 = 6, m=10, j=... Let's find j and ones such that left_idx gives 5, right_idx gives 6, and there is a far 1 that yields distance 4 via wrap. For d1=5 => j - left_idx =5 => left_idx = j-5. For d2=6 => right_idx - j =6 => right_idx = j+6. But right_idx must be ≤ m-1. So j+6 ≤9 => j ≤3. Also left_idx = j-5 ≥0 => j ≥5. Contradiction because j cannot be both ≤3 and ≥5. So impossible. More generally, with both neighbors defined, the sum d1+d2 = right_idx - left_idx ≤ m-1. If d1 > m/2 and d2 > m/2, sum > m, contradiction. So at least one of d1,d2 ≤ floor((m-1)/2). Hence the minimal circular distance cannot be less than min(d1,d2) because any other 1's circular distance is at least? Let's verify: If min(d1,d2) = d ≤ floor(m/2). For any other 1, either it is left of left_idx or right of right_idx. If it is left of left_idx, its absolute difference = j - k > j - left_idx = d1 ≥ d. The wrap distance m - (j - k) < m - d1. Since d1 >? Not sure. But could m - (j - k) be less than d? For it to be less, we need m - (j - k) < d => j - k > m - d. Since j - k ≥ d1+1 (since k ≤ left_idx-1). So we need d1+1 > m - d. If d is small (≤ m/2), m-d ≥ m/2. So we need d1+1 > m-d. Since d1 could be up to m-1, it's possible if d1 is large. But note if d1 is large, then d2 must be small because sum <= m-1. If d1 is large (close to m-1), then d2 is small (since sum = right_idx - left_idx ≤ m-1). Then min(d1,d2) would be d2 which is small. So in that case d = d2 (the small one). So min is already small. So the wrap distance to a far left 1 cannot be smaller than d2, because d2 is the distance to the right neighbor which is small. So indeed, when both neighbors exist, the minimal circular distance is min(d1, d2). Therefore our algorithm that computes min(left_dist, right_dist) with left_dist and right_dist as defined (including wrap when a side is missing) should correctly compute the minimal shift cost per row.
But wait: In the case both sides exist, we only consider left_dist = j - left_idx, right_dist = right_idx - j, and we don't consider the possibility that the minimal could be via a wrap to the left neighbor (i.e., using the right shift to bring that left neighbor). But as argued, that would be m - left_dist, which is greater than or equal to min(d1, d2) because if left_dist > m/2 then min(d1, d2) = d2 (since d2 = right_idx - j). And m - left_dist might be less than d2? Let's test: Suppose left_dist = 6, d2 = 4, m=10. Is it possible? Sum = left_idx? left_idx and right_idx: left_dist=6 => j-left_idx=6; right_dist=4 => right_idx - j =4; sum=10 => right_idx - left_idx =10. But indices: right_idx - left_idx = (j+4) - (j-6) =10. That's possible only if right_idx - left_idx =10. Since max index difference is 9 (0 to 9), 10 is impossible. So cannot happen. If left_dist=6, d2 must be ≤3 because sum ≤9. So d2 ≤3. Then min = d2=3. And m-left_dist=4, which is >3. So not better. So safe.
Thus our algorithm per row:
-
If no '1' in row: overall impossible -> -1.
-
Compute left_idx array (closest 1 on left, or -1 if none)
-
Compute right_idx array (closest 1 on right, or -1 if none)
-
Determine first_one, last_one.
-
For each column j:
left_dist = j - left_idx[j] if left_idx[j] != -1 else j + (m - last_one)
right_dist = right_idx[j] - j if right_idx[j] != -1 else (m - j) + first_one
d = min(left_dist, right_dist)
add to total for column j (or accumulate in array total_moves[j] += d)
But careful: The distances computed as above might exceed m/2? But that's okay; min will choose the smaller.
Double-check edge cases:
- If there is a 1 exactly at column j, then left_idx[j] = j (since row[j]=='1', so during left_idx pass: when we hit j, we set prev=j, then left_idx[j] = j; similarly right_idx[j] = j. Then left_dist = j - j = 0; right_dist = j - j =0; d=0. Good.
- If there is only one 1 in the row, say at position k. Then first_one = last_one = k. For any j:
left_idx[j] = k if j >= k else -1? Actually left_idx is the closest 1 on left (≤ j). So if j >= k, left_idx[j]=k; else -1. right_idx[j] = k if j <= k; else -1. Then:
For j >= k: left_dist = j - k; right_dist = (m - j) + first_one (since right_idx=-1). So d = min(j - k, (m - j) + k). That's the correct circular distance.
For j <= k: left_dist = j + (m - k); right_dist = k - j; d = min(j + (m - k), k - j). That's also correct.
- For multiple ones, check random.
Thus, for each row we can compute distances in O(m) time.
Total complexity: O(n*m). n <= 100, m <= 10000, so up to 1e6 operations, which is fine.
Now after computing total_moves per column (size m), we take the minimum. Output that minimum.
But careful: The moves are per row: each row can be shifted independently, and we sum the distances. Since each move is a shift of a whole row, we can perform them in any order; total cost is sum of costs per row to align 1 at the target column. This is correct because rows are independent; we don't need to coordinate shifts among rows.
Now need to implement.
Edge Cases:
-
If any row has no 1, answer -1.
-
If n=1, answer is min over j of distances for that row (i.e., minimal moves to get a 1 at some column). But the problem asks to make some column consist only of 1s. For n=1, we need that column to be 1. So we can shift to bring a 1 to any column, so the answer is the minimal distance from that row to any 1? Actually we need a column with all rows (only row) being 1. So we need to shift so that at some column j, the value is 1. That minimal moves is the minimal distance from current 1 positions to any column j? But we can also choose which column j to target. So the answer is min_j d[0][j] (where d[0][j] is min moves to get 1 at column j). That's what our algorithm does.
-
For m=1, shifts are trivial because shifting doesn't change anything (cyclic shift of length 1 is identity). So if all rows have 1, answer is 0; if any row has 0, answer -1.
Now we need to ensure correct modulo arithmetic.
Implementation details:
Read n, m. Then read n strings of length m.
Initialize total = [0]*m.
For each row i:
if '1' not in row: print -1 and exit.
Compute left = [-1]*m
prev = -1
for j in range(m):
if row[j] == '1':
prev = j
left[j] = prev
Compute right = [-1]*m
nxt = -1
for j in range(m-1, -1, -1):
if row[j] == '1':
nxt = j
right[j] = nxt
first_one = left[m-1]? Actually first_one is the first index where row[j]=='1'. Could find by scanning from start until found, but we have left array; left[m-1] gives the last 1 from left up to end, which is the rightmost 1? Not exactly. Better to find explicitly: first_one = row.find('1') ; but it's string, we can use row.index('1')? Could just scan to find first one, but since m up to 10000, we can find while reading row or after. For simplicity, we can compute first_one as the first index j where row[j]=='1'. And last_one as the last index. We can compute by scanning once:
first_one = -1; last_one = -1
for j in range(m):
if row[j]=='1':
if first_one == -1: first_one = j
last_one = j
This scan can be combined with building left or right? Actually we can compute first_one and last_one while building left/right? We can compute them separately with a simple loop before or after. Since m is not huge, extra O(m) per row is fine.
Then for each column j:
if left[j] != -1:
left_dist = j - left[j]
else:
left_dist = j + (m - last_one) # note: last_one must exist (since row has a 1)
if right[j] != -1:
right_dist = right[j] - j
else:
right_dist = (m - j) + first_one
d = min(left_dist, right_dist)
total[j] += d
After all rows, answer = min(total). Print answer.
Test with given examples.
Example 1:
3 6
101010
000100
100000
Row1: "101010". Indices (0-based): 0,2,4 are 1. Let's compute manually? We'll test later.
Row2: "000100": 1 at index 3.
Row3: "100000": 1 at index 0.
Compute totals per column.
I'll manually compute to verify answer=3.
First row distances: positions 0..5.
Ones at 0,2,4.
For each j:
j=0: d=0 (1 present)
j=1: nearest 1? left:0 dist1; right:2 dist1; min=1.
j=2: d=0.
j=3: left:2 dist1; right:4 dist1; min=1.
j=4: d=0.
j=5: left:4 dist1; right:0? wrap: right_dist = (6-5)+first_one(0)=1+0=1; left_dist=1 (5-4=1); min=1.
So row1 d: [0,1,0,1,0,1]
Row2: "000100", one at index3.
first=3, last=3.
Compute distances:
j=0: left_dist: left_idx = -1? Actually left[0] = -1, left_dist = 0 + (6-3)=3; right_dist: right_idx=3, dist=3-0=3; min=3.
j=1: left_idx=-1? since row[0] is 0, left[1] still -1 because we haven't seen a 1 yet. Actually scanning left: prev set when see 1; at j=1, no 1 yet, so left[1]=-1. left_dist=1+(6-3)=4; right_dist: right_idx=3 => 3-1=2; min=2? But also left_dist via wrap? Let's compute correctly: We'll compute with formula. left_dist = j + (m - last_one) = 1+3=4; right_dist = 3-1=2; min=2.
j=2: left_idx=-1? Actually at j=2, left still -1 (since 1 at 3 hasn't been encountered yet in left scan? left scan goes from left to right; at j=2, we haven't seen a 1 yet (since 1 at index3 >2). So left[2] = -1. left_dist = 2+3=5; right_dist = 3-2=1; min=1.
j=3: left_idx=3 (since when j=3, we see 1 and set prev=3, left[3]=3); left_dist=0; right_idx=3; right_dist=0; min=0.
j=4: left_idx=3 (since prev remains 3); left_dist=4-3=1; right_idx? right[4] = ? scanning from right: for j=4, next 1? from right: at j=5? Actually row[5]=0, so nxt at j=5? Let's compute right array: start from j=5: row[5]=0 => nxt stays -1 (since no 1 yet). So right[5] = -1. Then j=4: row[4]=0, so right[4] = -1 (since nxt still -1). j=3: row[3]=1, set nxt=3, right[3]=3. j=2: right[2]=3, etc. So for j=4, right[4] = -1 (since no 1 to the right in the linear sense). So right_dist = (6-4)+first_one(3)=2+3=5? Wait formula: right_dist = (m - j) + first_one = (6-4)+3=2+3=5. left_dist=1. So min=1.
j=5: left_idx=3, left_dist=5-3=2; right_dist = (6-5)+3=1+3=4; min=2.
Thus row2 d: [3,2,1,0,1,2]? Actually j=4 gave 1, j=5 gave 2. So row2 d: index0:3, 1:2, 2:1, 3:0, 4:1, 5:2.
Row3: "100000", one at index0. first=0, last=0.
Distances:
j=0: d=0.
j=1: left_idx? left[1] = 0 (since prev set at 0), left_dist=1; right_idx? right[1] = ? from right scan: at j=5:0, nxt=-1; j=4:0, nxt=-1; ... j=1:0, nxt? Eventually at j=0 we set nxt=0. So right[1] = 0? Actually scanning from right: at j=0 we set nxt=0, then for j>0, nxt stays 0? Let's compute properly: Start nxt = -1. For j from m-1 (5) down to 0:
j=5: row[5]='0' => nxt remains -1; right[5] = -1.
j=4: row[4]='0' => right[4] = -1.
j=3: row[3]='0' => right[3] = -1.
j=2: row[2]='0' => right[2] = -1.
j=1: row[1]='0' => right[1] = -1? Because nxt still -1 until we see a 1. Then j=0: row[0]='1' => set nxt=0, right[0]=0. So right[1] is set before j=0? Actually we traverse from high to low, so when j=1, we haven't processed j=0 yet. So at j=1, nxt is still -1 (since we haven't encountered a 1 yet going backwards). So right[1] = -1. That's correct: from index 1, there is no 1 to the right (in linear indices ≥1) because the only 1 is at index 0 which is less than 1. So right_idx[1] = -1. Then right_dist = (6-1)+first_one(0)=5+0=5. left_dist=1. So d=1. Similarly j=2: left_dist=2, right_dist = (6-2)+0=4, min=2. j=3: left_dist=3, right_dist=3, min=3. j=4: left_dist=4, right_dist=2? Actually right_dist = (6-4)+0=2, min=2. j=5: left_dist=5, right_dist=(6-5)+0=1, min=1.
Thus row3 d: [0,1,2,3,2,1].
Now total per column (sum):
col0: 0+3+0=3
col1: 1+2+1=4
col2: 0+1+2=3
col3: 1+0+3=4
col4: 0+1+2=3
col5: 1+2+1=4
Minimum = 3. Output 3 matches.
Great.
Now second example:
2 3
111
000
Row2 has no 1 -> answer -1. Works.
Edge Cases:
If multiple rows have 1, but some column yields minimal sum. Good.
Now we need to consider that m can be up to 10^4, and n up to 100, sums up to 1e6, fine.
Implementation in Python:
We'll read input using sys.stdin. We'll store total as list of ints of length m, initialized to 0.
We'll loop over rows.
But careful: For each row, we compute distances and add to total. Could also compute total after processing all rows; but it's fine.
If we encounter a row with no '1', we print -1 and exit.
Complexities fine.
Now we need to be careful about Python speed: n*m = 1e6, plus some overhead, it's fine.
Double-check the formula for left_dist when left_idx = -1: left_dist = j + (m - last_one). But is that always correct? Let's derive: When there is no 1 on left, all 1s have index > j. The nearest 1 via left direction (i.e., moving left) would be the one with the largest index (rightmost 1) because that gives the smallest left distance? Actually earlier we argued that when moving left from j, the distance to a 1 at index k (> j) is (j - k) mod m = m - (k - j). This is decreasing as k increases. So the minimal left distance is achieved for the maximum k, i.e., last_one. So left_dist = m - (last_one - j)? Wait compute: For k = last_one, left distance = (j - last_one) mod m = m - (last_one - j) because last_one > j. So left_dist = m - (last_one - j) = (j + m) - last_one? Actually m - (last_one - j) = m - last_one + j = j + (m - last_one). So correct.
Similarly, when right_idx = -1, all 1s have index < j. The nearest via right direction is the smallest index (first_one) because right distance = (k - j) mod m = m - (j - k) = (m - j) + k. For k = first_one, distance = (m - j) + first_one. So correct.
Edge: When both left_idx and right_idx are -1? That would mean no 1 at all, but we already check that.
Now, what about when left_idx exists but is -1? Already handled.
One more nuance: For left_dist when left_idx exists, we use j - left_idx. But could it be that the minimal left distance is achieved by a 1 that is not the immediate left neighbor? As argued earlier, when left_idx exists, the immediate left neighbor gives the smallest absolute difference on left side, but the circular distance to that neighbor might not be j-left_idx; it could be m - (j - left_idx) if that is smaller. However, the minimal distance for that neighbor is min(j-left_idx, m - (j-left_idx)). Since we are taking min(left_dist, right_dist) and left_dist = j-left_idx (not the min of the two directions for that neighbor), we might be missing the possibility that the minimal for that neighbor is m - (j-left_idx) and that could be smaller than both left_dist and right_dist. But as argued earlier, if j-left_idx > m/2, then m - (j-left_idx) < j-left_idx. However, in that case, due to the presence of a right neighbor (since left_idx exists, and if there is a 1 on right as well? Actually if left_idx exists, it doesn't guarantee a right neighbor exists. If right_idx is -1, then we are already computing right_dist as wrap distance, which might be smaller. But if right_idx also exists, then as argued sum condition ensures that j-left_idx cannot be > m/2 while also having a right neighbor? Let's check again: Could we have left_idx exists and right_idx exists, and j-left_idx > m/2, but the minimal distance to that left neighbor via wrap (i.e., m - (j-left_idx)) is actually smaller than both left_dist (which is j-left_idx) and right_dist (right_idx - j)? It would require m - (j-left_idx) < right_dist. Since right_dist = right_idx - j. And we have left_idx and right_idx are consecutive ones in sorted order? Not necessarily consecutive in the sense of no other ones in between, but they are the immediate left and right neighbors. Then left_idx < j < right_idx. Then right_dist = right_idx - j. Since left_idx and right_idx are indices, we have right_idx - left_idx = (right_idx - j) + (j - left_idx) = right_dist + left_dist. This sum ≤ m? Actually it's at most m-1 (since indices are within 0..m-1). If left_dist > m/2, then right_dist = (right_idx - left_idx) - left_dist ≤ (m-1) - (floor(m/2)+1) = roughly m/2 -1. So right_dist < m/2. So right_dist < left_dist, and also m - left_dist = m - left_dist. Since left_dist > m/2, m - left_dist < m/2. Compare m - left_dist with right_dist: could it be that m - left_dist < right_dist? That would mean m - left_dist < right_dist => m < left_dist + right_dist = right_idx - left_idx, which is impossible because right_idx - left_idx ≤ m-1 < m. So m - left_dist cannot be less than right_dist. Actually m - left_dist >? Let's derive: m - left_dist < right_dist ? This is equivalent to m < left_dist + right_dist, but left_dist+right_dist = right_idx - left_idx ≤ m-1, so m ≤ m-1? Impossible. So m - left_dist ≥ right_dist + 1? Actually m - left_dist > right_dist? Let's test: Suppose m=10, left_dist=6, then right_dist = (right_idx - left_idx) - 6. The maximum right_idx - left_idx could be 9, so right_dist max = 3. Then m - left_dist = 4, which is >3. So indeed m - left_dist > right_dist. So the wrap distance to left neighbor is greater than right_dist. So min(left_dist, right_dist) would pick right_dist, which is smaller. So it's fine.
Thus our min(left_dist, right_dist) indeed yields the true minimal circular distance.
Now we should implement.
Potential pitfalls:
- Off-by-one: Indices 0-based vs 1-based? We'll use 0-based. The shifting distances are number of moves, which is independent of indexing base. So using 0-based is fine.
- The total moves may be large: worst-case each row may require up to floor(m/2) moves, n=100, m=10000 => max total = 100*5000 = 500,000, fits in int.
- Input reading: lines may have trailing newline. We'll strip.
Now let's implement in Python.
We'll write solve() function:
import sys
def solve():
import sys
data = sys.stdin.read().split()
if not data: return
it = iter(data)
n = int(next(it))
m = int(next(it))
rows = []
for _ in range(n):
rows.append(next(it).strip())
total = [0]*m
for row in rows:
if '1' not in row:
print(-1)
return
# find first_one and last_one
first_one = row.find('1')
last_one = row.rfind('1')
# compute left_idx array
left = [-1]*m
prev = -1
for j in range(m):
if row[j] == '1':
prev = j
left[j] = prev
# compute right_idx array
right = [-1]*m
nxt = -1
for j in range(m-1, -1, -1):
if row[j] == '1':
nxt = j
right[j] = nxt
# accumulate distances
for j in range(m):
if left[j] != -1:
left_dist = j - left[j]
else:
left_dist = j + (m - last_one)
if right[j] != -1:
right_dist = right[j] - j
else:
right_dist = (m - j) + first_one
d = left_dist if left_dist < right_dist else right_dist
total[j] += d
ans = min(total)
print(ans)
if name == "main":
solve()
Check example:
First sample should output 3.
Second sample: row2 has no '1' -> -1.
Now test additional cases:
Case: n=1, m=5, row="00100". Ones at index2. distances: for j=0: min(0+? left_dist? left_idx=-1? Actually left_idx[0] = -1, left_dist = 0 + (5-2)=3; right_dist = right_idx? right[0] = 2? Let's compute: right array: from right: j=4:0, nxt=-1; j=3:0; j=2:1 set nxt=2; j=1: right[1]=2; j=0: right[0]=2. So right_dist = 2-0=2; min=2. But the actual minimal moves to bring 1 to column0: from index2, left shift by? To bring 1 from index2 to 0: shift left twice? Actually if we shift left, the element moves left. Starting at col2, after t left shifts, it goes to (2 - t) mod 5. For t=2, goes to 0. So distance=2. Or shift right 3 steps -> 3 moves. So min=2. So our d=2 correct. For j=1: left_idx? left[1] = -1? Actually left scan: prev at j=0 is -1; at j=1, still -1; so left_dist = 1+3=4; right_dist = right[1]=2-1=1 => min=1 (shift right 1? Actually from 2 to 1: left shift 1 or right 4, min=1). Good. j=2: d=0. j=3: left_idx=2, left_dist=1; right_idx? right[3] = -1? Let's compute right: from right, after setting nxt=2 at j=2, for j=3, nxt is still 2? But careful: When scanning from right, we start at j=4, nxt=-1; j=3: row[3]=0 => right[3] = -1 (since nxt still -1). Actually because we haven't encountered a 1 yet when going from right side: we go from high to low, and we set nxt when we see a 1. At j=2 we see 1 and set nxt=2. But then for j=3 (which we process before j=2? Since we go from m-1 down to 0, the order is: j=4, j=3, j=2, j=1, j=0. So when processing j=3, we haven't processed j=2 yet, so nxt is still -1. So right[3] = -1. That's correct because from index 3, there is no 1 to the right (indices >=3) except possibly index 4? But there is none. So right_dist = (5-3)+first_one=2+2=4; left_dist=1; min=1. So d=1. Actually the actual distance from 2 to 3: shift right 1 or left 4, min=1. Good. j=4: left_idx=2, left_dist=2; right_idx = -1? right[4] = -1 (since j=4 processed before seeing any 1). right_dist = (5-4)+2=1+2=3; min=2. So row distances: [2,1,0,1,2]. min total for a column is 0, but we need to choose column j that yields all rows (just one) to be 1. So answer = 0 because column2 already is 1. Our algorithm would sum (only one row) total per column = those distances, then min = 0. Good.
Now test case where m=1:
n=2, m=1
1
1 -> row1 has 1, row2 has 1. first_one=0, last_one=0. For each row: left[0]=0? For j=0: left_idx=0, left_dist=0; right_idx=0, right_dist=0. total[0] added 0. After both rows, total[0]=0, answer=0. Good.
n=2, m=1
1
0 -> row2 has no 1, answer -1. Good.
Now test random case to ensure distances are correct.
Potential bug: In computing left_dist when left_idx != -1, we use j - left[j]. But what if left[j] > j? That can't happen because left[j] is the last seen 1 up to j, so left[j] <= j. So fine.
Similarly right[j] >= j or -1.
Now about the formula for left_dist when left_idx == -1: left_dist = j + (m - last_one). But is this always correct even if last_one is the same as first_one? Yes.
Similarly, right_dist when right_idx == -1: (m - j) + first_one.
Now we must also consider the case where left_idx != -1 but the minimal left distance might be via wrap to some other 1 (not the immediate left) that yields a smaller distance than both left_dist and right_dist? As argued earlier, not possible when both left and right neighbors exist; if right neighbor missing, we already consider wrap right distance. So safe.
Thus solution seems correct.
Now time to code and test with given examples.
We should also consider possibility of m = 0? No, m>=1.
Now note: In Python, using row.find('1') gives -1 if not found, but we already checked '1' in row, so it's safe. However, if row has no '1', we exit early. So first_one and last_one are defined.
But we need to be careful: For large m, using .find and .rfind may be efficient, but we already scanned row to check '1' not in? Actually we do 'if '1' not in row' which scans the string anyway. Then we call row.find and row.rfind which scan again. That's okay (three scans per row). Alternatively, we can compute first_one and last_one during the left scan or right scan. But not necessary.
But note: If we use row.find('1') after checking '1' in row, it will scan again. Could combine: after checking, we can find first_one = row.index('1') (but index throws error if not found). But we know it's present, so .index works. However, simpler: first_one = row.find('1') (returns index). Since we know it's present, it's non-negative. last_one = row.rfind('1'). This is O(m) but okay.
Alternatively, we can compute first_one and last_one in the left/right loops: In left loop, when we see the first '1', we can set first_one if not set yet; but we need first_one for later, and left loop goes from left to right, so the first time we encounter a '1' (when prev changes from -1 to some j) we can record first_one. For last_one, we can record during right loop similarly. But it's fine.
Now test with sample:
Input:
3 6
101010
000100
100000
Our code: For row1, first_one = row.find('1') => index 0. last_one = row.rfind('1') => index 4? Actually "101010": positions: 0,2,4 are 1, so rfind returns 4. Good. Then compute left and right. Add to total. At end, ans=3. Good.
Second sample: row2 has no '1', prints -1.
Now consider scenario where n=100, m=10000, all rows have all 1s. Then for each row, distances d[i][j] = 0 for all j (since every column has 1). So total per column = 0. answer = 0. Good.
If rows have 1s but some columns may be impossible? Actually with all rows having at least one 1, always possible because we can shift each row to bring a 1 to some column. However, we need the same column for all rows. Since each row can be shifted independently, we can always choose a column and shift each row to bring a 1 there (since each row has at least one 1). But is it always possible? Yes, because for any column j, each row i can be shifted to bring some 1 to column j, as long as row has at least one 1. So it's always possible. So answer is never -1 if every row has at least one 1. But wait, consider if a row has 1s but maybe the column j is such that we cannot bring a 1? Actually with cyclic shifts, any 1 can be moved to any column, because we can shift to align that 1 to the target column. The number of moves is the circular distance. So for each row and each column, there is a finite distance (the minimal circular distance to a 1). So it's always possible. Thus the only impossibility is when some row has no 1. So early exit works.
Now final code.
But we must be cautious about reading input: The lines may have spaces? No, they are strings of 0/1. So using split() will separate them correctly.
Now produce final answer.
But before finalizing, let's test more:
Case: n=2, m=2
10
01
Row1: "10", ones at 0. Row2: "01", ones at 1.
Compute totals:
Row1 distances: for j=0:0, j=1: min(1? Actually from 0 to 1: distance 1). Row2 distances: j=0: from 1 to 0: distance 1; j=1:0. Total: col0:0+1=1; col1:1+0=1. Minimum=1. Indeed we can shift row1 right by 1 (or row2 left by 1) to get both 1s in column? Actually target column 0: row1 already 1, row2 need to shift left by 1 to bring its 1 from index1 to 0: cost 1. Or column1: row2 already 1, row1 shift right 1: cost 1. So answer 1.
Our code: row1: first=0, last=0. left: j0: left=0; j1: left=0. right: j1: right? from right: j1= '0'? Actually row1 "10": indices: 0='1',1='0'. right array: j1: since row1[1]=0, and scanning from right: start nxt=-1; j=1: row1[1]=0 => right[1]=-1; j=0: row1[0]=1 => nxt=0, right[0]=0. So for j=1: right=-1, right_dist = (2-1)+first=1+0=1; left_dist=1-0=1; d=1. j=0: left_dist=0, right_dist=0, d=0. So row1 d: [0,1]. Row2: "01": first=1,last=1. left: j0: left=-1; j1: left=1. left_dist for j0: left=-1 => left_dist=0+(2-1)=1; right: right array? j0: right? scanning from right: j1: row2[1]=1 => nxt=1, right[1]=1; j0: row2[0]=0 => right[0]=1? Actually at j=0, after processing j=1 we set nxt=1; then j=0, row2[0]=0, so right[0] = nxt =1. So right_dist = 1-0=1; d=1. j1: left_dist=0, right_dist=0, d=0. So row2 d: [1,0]. Totals: col0:0+1=1, col1:1+0=1. min=1. Good.
Now test where row has ones but we might incorrectly compute distances due to wrap handling. Let's test row: m=5, row="00101". Ones at indices 2 and 4? Actually "00101": index0=0,1=0,2=1,3=0,4=1. So first_one=2, last_one=4. Compute distances manually:
For each j:
j0: nearest 1? distances: to 2: right dist=2, left dist via wrap to 4: (0-4) mod5 =1? Actually circular distance: min(|0-2|=2, 5-2=3) =2; to 4: min(4,1)=1. So min =1. Our algorithm: left_idx[0] = -1 (since no 1 ≤0), left_dist = 0 + (5-4)=1. right_idx[0] = 2 (since right scan: from right, at j4 see 1? Let's compute right: start nxt=-1; j4=1 => nxt=4, right[4]=4; j3=0 => right[3]=4; j2=1 => nxt=2, right[2]=2; j1=0 => right[1]=2; j0=0 => right[0]=2. So right_dist = 2-0=2. min=1. Good.
j1: left_idx[1] = -1 (since no 1 ≤1), left_dist = 1+1=2; right_idx[1]=2, right_dist=1; min=1. Circular min: distances to 2:1, to4: min(3,2)=2 -> min=1. Good.
j2: left_idx[2]=2, left_dist=0; right_idx[2]=2? Actually right[2]=2? At j2, right[2] = 2 (since after j2 we set nxt=2? But careful: In right scan, when we get to j2, we see '1' and set nxt=2, so right[2]=2). So right_dist=0; d=0.
j3: left_idx[3]=2, left_dist=1; right_idx[3]=4 (since right[3]=4), right_dist=1; min=1. Circular: to 2:1, to4:1 ->1.
j4: left_idx[4]=4, left_dist=0; right_idx[4]=4; d=0.
So works.
Now test row: "01010", m=5, ones at 1,3. first=1, last=3. Compute distances manually:
j0: to1:1, to3: min(3,2)=2 -> min=1. Our algorithm: left_idx[0]=-1, left_dist=0+(5-3)=2; right_idx[0]=1, right_dist=1; min=1.
j1: 0.
j2: left_idx[2]=1, left_dist=1; right_idx[2]=3, right_dist=1; min=1. Circular: to1:1, to3:1 ->1.
j3:0.
j4: left_idx[4]=3, left_dist=1; right_idx[4]=? right[4]: scanning: j4=0, j3=1 set nxt=3, so right[4] = 3? Actually right[4] will be -1? Let's compute: start nxt=-1; j4=0 => right[4]=-1; j3=1 => set nxt=3, right[3]=3; j2=0 => right[2]=3; j1=1 => set nxt=1, right[1]=1; j0=0 => right[0]=1. So right[4] = -1. So for j4: left_dist=4-3=1; right_dist = (5-4)+first=1+1=2; min=1. Circular: to3:1, to1: min(3,2)=2 ->1. Good.
Thus algorithm seems solid.
Now we need to consider that the total_moves per column may be large, but we take min.
Potential overflow? Python ints unlimited.
Now we are ready to write final solution.
But wait, there is a nuance: The problem says "cyclically shift its values either one cell to the left, or one cell to the right." Each move shifts a row by exactly one cell. So the distance we compute (min circular distance) is indeed the minimal number of such unit shifts to bring a specific 1 to column j. Since we can choose which 1 to bring, it's the min over all 1s of the circular distance. Our d[i][j] is that. So sum over rows gives total moves. Yes.
Now, are there any constraints about doing multiple moves on same row? Yes, we can shift a row multiple times; each shift counts as one move. So the total is sum of distances.
Now, the solution seems correct.
Now we must ensure that we correctly handle the case where m is 1. In that case, first_one = 0, last_one = 0. left array: for j=0, left[0] = 0 (since row[0]=='1'?), but if row has '1', yes. right array: right[0]=0. Then left_dist = 0, right_dist=0. So total fine. If row has '0', we exit.
Now, I'd like to test with random small cases to verify against a brute-force solver. Let's quickly do mental test with n=2, m=3, all possible rows? But trust.
Thus final code as above.
But we need to consider memory: total array of size m (max 10k) is fine.
Now one more nuance: The input may have spaces? The lines are strings of length m, no spaces. So reading with split() works.
Now let's finalize answer.
Potential optimization: Instead of storing left and right arrays of length m for each row, we could compute distances on the fly with two passes, but it's easier to store.
But we can also compute distances without storing left/right arrays, by doing a single pass per row: For each row, we can compute the distances by using the positions of ones. However, storing arrays is fine given constraints.
Now think about alternative: For each row, we could compute distances using BFS from all 1 positions simultaneously, since the distance function on a cycle is simple, but our method is fine.
Now let's consider if there is any scenario where the minimal total moves might be achieved by not aligning each row to the target column with minimal moves? Could it be beneficial to shift a row more than the minimal distance to bring a 1 to the target column, in order to reduce moves for other rows? No, because rows are independent; the target column is common but each row's shifts affect only that row. The cost for a row to get a 1 at column j is the minimal circular distance to a 1. If we shift more than necessary, we would increase the cost for that row without affecting others. So minimal total for column j is sum of minimal distances. So we are correct.
Thus answer is min over j of sum_i d[i][j].
Now we can implement.
Now edge: For very large m, the computation of right array using Python loops may be a bit slower, but 1e6 operations is fine.
Potential micro-optimizations: Use list comprehension or precompute positions of ones and then for each j compute distances by scanning? Could be slower.
Given we are within time, it's okay.
Now let's produce final solution.
But there is a subtle bug: In our algorithm, when both left_idx and right_idx are not -1, we compute left_dist = j - left_idx, right_dist = right_idx - j. But what about the case where the row has exactly one 1 and j equals that index? Then both left_idx and right_idx are that index, and distances are 0. Works. For j not equal, one of them is -1, and we compute wrap distances accordingly. For row with multiple ones, we may have both non -1.
Now think about a row with ones at indices 0 and 1, m=5. For j=4: left_idx = 1 (since largest ≤4), right_idx =? There is no index ≥4 with a 1, so right_idx = -1. left_dist = 4-1=3; right_dist = (5-4)+first_one(0)=1+0=1; min=1. Actual minimal: to bring 0 to 4, distance = min(4,1)=1; to bring 1 to 4, min(3,2)=2; so min=1. Good.
Now for j=2: left_idx=1, right_idx? Since ones at 0 and 1? Actually right_idx = ? There is no index ≥2 with a 1, so right_idx = -1. left_dist = 2-1=1; right_dist = (5-2)+0=3+0=3; min=1. Actual minimal: to 1: distance 1; to 0: distance min(2,3)=2. So min=1.
But wait, there is also a 1 at index 0, which is left of j, so left_idx is the largest ≤ j, which is 1 (since 1 > 0). So left_idx=1 is correct. But we didn't consider the possibility of using the 1 at index 0 via right wrap? That would be moving rightwards from j=2 to 0: (0-2) mod 5 = 3? Actually right distance to 0 = (0 - 2) mod 5 = 3, but left distance to 0 = 2, so min=2. So not better.
All good.
Thus implementation is correct.
Now we should also think about the possibility of using a different algorithm: For each column j, we could compute for each row the distance by scanning the row to find the nearest 1 on both sides. That would be O(nm^2) if naive. Our O(nm) is good.
Now let's write final answer.
But before final, I want to consider if there is any trick: m up to 10^4, and we need to store total of length m. That's fine.
Now we will produce final solution in Python.
I'll also add comment for clarity.
Now final code:
import sys
def solve():
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
rows = [next(it).strip() for _ in range(n)]
INF = 10**9 # not needed
total = [0] * m
for row in rows:
if '1' not in row:
print(-1)
return
# find first and last 1 positions
first_one = row.find('1')
last_one = row.rfind('1')
# left closest 1 index
left = [-1] * m
prev = -1
for j in range(m):
if row[j] == '1':
prev = j
left[j] = prev
# right closest 1 index
right = [-1] * m
nxt = -1
for j in range(m-1, -1, -1):
if row[j] == '1':
nxt = j
right[j] = nxt
# accumulate distances
for j in range(m):
if left[j] != -1:
left_dist = j - left[j]
else:
left_dist = j + (m - last_one)
if right[j] != -1:
right_dist = right[j] - j
else:
right_dist = (m - j) + first_one
total[j] += left_dist if left_dist < right_dist else right_dist
print(min(total))
if __name__ == "__main__":
solve()
Check that for row like "1", m=1: first_one=0, last_one=0, left[0]=0, right[0]=0, left_dist=0, right_dist=0, total[0] gets 0. Good.
Now test with sample.
Now we can consider optimization: We can avoid storing left and right arrays by using two passes directly to compute distances per column and add to total. But simpler to keep.
But note: In the accumulation loop, we are adding to total[j] the minimum distance for that row. We could also compute total array column by column by scanning each row and updating. That's what we do.
Now, potential off-by-one: In the left_dist formula for wrap: left_dist = j + (m - last_one). For j=0 and last_one=0, left_dist = 0 + (m-0) = m. But if last_one=0, that means there is a 1 at index0. But if left_idx == -1, that implies there is no 1 ≤ j. For j=0, if last_one=0, then there is a 1 at index0, so left_idx[0] should be 0, not -1. So this case won't occur. Good.
Similarly, right_dist wrap formula: (m - j) + first_one. For j=m-1 and first_one=m-1, if right_idx==-1, then j=m-1 and there is no 1 ≥ m-1; but if first_one=m-1, then there is a 1 at m-1, so right_idx would be m-1, not -1. So fine.
Now, we can also compute distances using a BFS-like "distance to nearest 1" on a circle, but fine.
Now final answer.
But there is a nuance: The problem's example says "cyclically shift the second row to the right once, then shift the third row to the left twice." That matches our distances: row2 originally had 1 at col3 (0-indexed 3) and target column? They made column before last: column 4? Actually they said "the table column before the last one will contain only 1s." In 0-indexed, columns: 0 1 2 3 4 5. Before last is column 4 (since last is 5). Our minimal total for column 4 was 3 (row1:0, row2:1, row3:2) -> total 3. Indeed row2 needed 1 move (right shift once) and row3 needed 2 moves (left twice). So matches.
Now, could there be a scenario where the minimal total is achieved by a column that requires some rows to use more than the minimal distance? As argued, no, because each row's cost is independent.
Thus final solution.
Now I will produce final answer. ```python
import sys
def solve() -> None:
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
rows = [next(it).strip() for _ in range(n)]
# total moves needed for each column
total = [0] * m
for row in rows:
# If a row has no '1', it's impossible
if '1' not in row:
print(-1)
return
# positions of first and last '1' in the row
first_one = row.find('1')
last_one = row.rfind('1')
# left_nearest[j] = index of closest '1' with index <= j (or -1)
left = [-1] * m
prev = -1
for j in range(m):
if row[j] == '1':
prev = j
left[j] = prev
# right_nearest[j] = index of closest '1' with index >= j (or -1)
right = [-1] * m
nxt = -1
for j in range(m - 1, -1, -1):
if row[j] == '1':
nxt = j
right[j] = nxt
# for each column compute minimal moves for this row
for j in range(m):
# distance by moving left (or left + wrap if no left neighbour)
if left[j] != -1:
left_dist = j - left[j]
else:
left_dist = j + (m - last_one)
# distance by moving right (or right + wrap if no right neighbour)
if right[j] != -1:
right_dist = right[j] - j
else:
right_dist = (m - j) + first_one
total[j] += left_dist if left_dist < right_dist else right_dist
# best column
print(min(total))
if name == 'main':
solve()