We are given a 2D grid of integers. We need to find the number of "crosses" of 1s. A cross is defined as a 1 with four arms of equal length. That means we have a center cell that is 1, and there are four directions: up, down, left, right. Each arm extends from the center with consecutive 1s. The arms must have the same length. The arms can be of length >=1? Typically, a cross could be of arm length at least 1, meaning at least one cell in each direction besides the center? Or could it be just the center without arms? Let's interpret: "A cross is a 1 with four arms of equal length." The center is the 1 itself? Or maybe the cross includes the center? Usually, a cross shape includes a central cell and arms extending in four directions. The arms have equal length. So the minimal cross would be just the center (center only) with arm length 0? That wouldn't have arms. Usually, arms must have at least length 1. But the problem statement: "a 1 with four arms of equal length." That suggests that we have a central 1 and from that central 1, we have arms of equal length. The arms are sequences of 1s. So if the arm length is 1, then we have center and one cell in each direction, total 5 cells. If arm length is 2, center plus two cells in each direction, total 9 cells. So we need to count all such centers that have arms of equal length (>=1). But could it be that arms of length 0 are considered? That would be just a single 1, but that's not a cross because there are no arms. So probably we require arms length at least 1.
We need to count number of crosses. Overlapping crosses? If there is a larger cross, does it also contain smaller crosses? Possibly. The problem is: we need to find all positions that serve as the center of a cross of equal arm lengths. So we need to check for each cell that is 1, whether there exist consecutive 1s in all four directions, and the maximum arm length possible in each direction. For a cross to exist, we need at least arm length 1 in each direction. But also arms must be equal length. So we need to find the maximum possible arm length in each direction (the count of consecutive 1s starting from the center outward until a non-1 or boundary). Let up[i][j] = number of consecutive 1s upward from (i,j) (including (i,j) or not? Typically we want the length of the arm excluding the center? The arm is from the center outward. If we count the center as part of the arm? Usually the arm includes the center? Let's define: For a cross centered at (i,j), the arm length L means that there are L cells in each direction from the center, including maybe the center? Let's define: If we say arm length = 0, then only center. arm length = 1: center + immediate neighbor up, down, left, right. So the total number of cells in the cross is 1 + 4*L. So for each cell, compute the number of consecutive 1s in each direction starting from that cell and going outward (excluding the cell itself or including?). We'll want to know: if we have a center at (i,j), then the arm length upward is the number of consecutive 1s directly above (i,j) until a non-1 or edge. That's the number of cells in the up arm, not counting the center. Similarly down, left, right. So define up[i][j] = number of consecutive 1s in the upward direction starting from the cell (i-1,j) moving upward? Actually we can compute four DP arrays: up[i][j] = if grid[i][j]==1 then up[i-1][j]+1 else 0. That counts including current cell? Let's see: If up[i][j] is defined as the number of consecutive 1s ending at (i,j) from upward direction (i.e., vertically from top). That would include the current cell. But we need for a center, the number of cells upward from the center, not counting the center. So we can compute arrays that count the length of the streak in each direction that includes the current cell. Then for center (i,j), the upward arm length = up[i-1][j]? Not exactly. Let's define:
- up[i][j]: length of consecutive 1s ending at (i,j) going upward (i.e., number of 1s in column j from some starting row up to i). So if grid[i][j]==1, up[i][j] = up[i-1][j] + 1 else 0.
- down[i][j]: similar but from bottom, or we can compute downward length starting from (i,j). Another approach: compute for each cell the number of 1s in each direction including the cell. Then for center (i,j), the arm length upward is the number of consecutive 1s above (i,j), which is the count in that direction that includes the cell above? Actually if we want to count cells that are strictly above the center, we can compute a DP that gives the number of consecutive 1s starting at (i,j) and going upward (excluding (i,j)). But easier: compute arrays that give the length of consecutive 1s in each direction from the current cell outward. Many solutions for similar problems (like counting pluses) compute four arrays: left[i][j] = number of consecutive 1s to the left including the current cell; right[i][j] = to the right including; up[i][j] = upward including; down[i][j] = downward including. Then for a cell to be a cross center with arm length >=1, we need: left[i][j] >= 2, right[i][j] >= 2, up[i][j] >= 2, down[i][j] >= 2. Because for left, if left[i][j] includes the center and at least one more to the left, then the arm length (excluding center) is left[i][j] - 1. Similarly for others. So the maximum possible arm length (excluding center) is min(left[i][j]-1, right[i][j]-1, up[i][j]-1, down[i][j]-1). For a cross to have equal arm lengths, we need that the minimal of these four values (call it L) is at least 1. That would mean there exists an arm length L such that all four arms have at least L consecutive 1s (including center). But note: The cross definition: "a 1 with four arms of equal length." That suggests that for a given cross, the arms have a specific length. Could it be that we count each distinct cross shape? For a given center, if the maximal L is some value, then we have crosses of arm length 1,2,...,L? The problem likely asks: "number of crosses of 1s." That might mean we count each distinct cross pattern (like a specific shape) that appears in the grid. For example, if there is a large cross with arm length 3, that includes also smaller crosses with arm length 1 and 2? Does each count as a separate cross? Usually in problems like "count the number of crosses" they might mean count the centers that can be the center of at least one cross (i.e., have equal arms of any positive length). Or they might count each possible cross (i.e., each possible arm length). The phrasing: "find the number of 'crosses' of 1s. A cross is a 1 with four arms of equal length." That could be interpreted as: each occurrence of a cross shape (any arm length) counts as one. But if we have a large cross, does it contain multiple crosses? The cross shape is defined by the center and the arms. So if we have arm length 3, then the grid contains a cross of length 3. But also if we consider the same center with arm length 2, it's also a cross (since the arms of length 2 are also present). However, the cross of arm length 2 is a subset of the larger cross. Are we supposed to count both? Typically, problems that ask "count the number of crosses" count each distinct cross shape based on the center and the arm length. But if we have a big plus sign, it's still one plus sign; it's not broken into smaller plus signs unless they have different centers? Actually, a plus sign shape is defined by a specific arm length. If the grid has a long arm, you could say there exists a plus sign of length 3; but also there exists plus signs of length 2,1 at the same center if the arms extend sufficiently. However, most likely the problem intends to count each center that can be the center of a cross (i.e., at least one cross exists). Usually in coding challenge contexts: "count the number of crosses" where a cross is defined as a cell with 1's extending equally in all four directions. Typically they want to count the cells that have at least one neighbor in each direction (so minimal arm length 1) but also the arms must be of equal length, meaning that the distances to the next 0 or boundary in all four directions are equal. However, if arms can be longer than 1, then we need to consider that the arms could be of length >1. But does equality require that the lengths of arms (the maximal continuous stretch in each direction) are equal? That is, for a given center, the maximum possible arm length in each direction might be different. For it to be a cross, we need that we can choose an arm length L such that in each direction there are at least L consecutive 1s (starting from the center outward). The largest possible cross at that center would have L = min(up_len-1, down_len-1, left_len-1, right_len-1). So if L >= 1, then there exists at least one cross. But would we count the cross as the maximal one, or all possible L? The phrase "a cross is a 1 with four arms of equal length." That could be interpreted as each such configuration (center+arms) is a cross. So if the maximal L is 3, then we have crosses of lengths 1,2,3 at that center. They are distinct crosses because the arms have different lengths. However, they all share the same center. Is that considered multiple crosses? If you have a 5x5 cross of ones (like a plus sign with arms of length 2), then the grid has exactly one cross? Or could it be argued that there are multiple crosses of smaller sizes inside? The typical "plus sign" problem in LeetCode: "Largest Plus Sign" asks to find the largest order of plus sign, where order is arm length. That counts each center and order. But they don't count sub-orders separately; they want the maximum order. But here they ask "find the number of crosses". Could be they want to count how many such cross patterns exist in the grid, each defined by a center and an arm length. For example, if you have a 3x3 block of all 1s:
111
111
111
Each cell? For the center cell (1,1) (0-indexed), it has up: up[1][1] maybe? Let's compute: For center (1,1) (the middle), up = length upward including center? Actually with grid all 1s, up[i][j] counts consecutive 1s upward from top. If we compute DP: up[0][j] = 1 for all j. up[1][j] = up[0][j] + 1 = 2. up[2][j] = up[1][j] + 1 = 3. Similarly down: if we compute from bottom, down[2][j]=1, down[1][j]=2, down[0][j]=3. left: left[i][0]=1, left[i][1]=2, left[i][2]=3. right: right[i][2]=1, right[i][1]=2, right[i][0]=3. For center (1,1): up[1][1]=2, down[1][1]=2, left[1][1]=2, right[1][1]=2. So arm length (excluding center) = min(2-1,2-1,2-1,2-1)=1. So L_max=1. So we have a cross of length 1 (total 5 cells). Does the center (1,1) also have L=0? That would be just the cell itself, not a cross. So we count one cross. But also what about other cells? The corners? (0,0): up? Probably 1, left? Actually (0,0) is top-left corner: up=1 (only itself), down maybe 3? left=1, right maybe 3? But it doesn't have arms in all directions (lack up? up only cell itself, so arm length up=0). So not a cross. Edge centers? e.g., (0,1): up length = 1, down = 3, left = 2? Actually (0,1): left: left[0][1]=2? That includes (0,0) and (0,1) so left length including center is 2; right: right[0][1]=2? (0,1) and (0,2) gives 2? Actually right[0][1]=2? With 3 columns: right DP from right: right[i][j] = if grid[i][j]==1 then right[i][j+1]+1 else 0. So for row0: right[0][2]=1; right[0][1]=right[0][2]+1=2; right[0][0]=right[0][1]+1=3. So (0,1): up[0][1]=1, down[0][1]=3? down[0][1] computed from bottom: down[2][1]=1, down[1][1]=2, down[0][1]=3. left[0][1]=2, right[0][1]=2. So min(up-1=0, down-1=2, left-1=1, right-1=1) = 0, so no cross (arm length must be >=1). So only center yields a cross. So total crosses =1.
But what about a larger cross, say a 5x5 cross shape: all cells in the middle row and middle column are 1, others 0. That's a cross of arm length 2. That grid: For the center (2,2), up: 3? Actually compute up DP: rows: row0: maybe only column2 cells are 1? Let's be systematic:
grid:
0 0 1 0 0
0 0 1 0 0
1 1 1 1 1
0 0 1 0 0
0 0 1 0 0
That's a cross of arm length 2 (center at (2,2)). For center (2,2): up[2][2] =? up counts consecutive 1s upwards including current. Up: from top: row0 col2=1, row1 col2=1, row2 col2=1. So up[2][2] = up[1][2]+1 =? up[0][2]=1, up[1][2]=2, up[2][2]=3. down: from bottom: down[4][2]=1, down[3][2]=2, down[2][2]=3. left: left DP: left[2][0]=1, left[2][1]= if grid[2][1]=1? Actually row2: columns 0,1,2,3,4 are all 1. So left[2][0]=1, left[2][1]=2, left[2][2]=3, left[2][3]=4? Wait left DP: left[i][j] = if grid[i][j]==1 then (j>0? left[i][j-1]+1 else 1). So left[2][2] = left[2][1] + 1 = 2+1=3. Actually left[2][1] = left[2][0] + 1 = 1+1=2. left[2][0]=1. So left[2][2]=3. Similarly right: right[2][4]=1, right[2][3]=2, right[2][2]=3. So for center: up[2][2]=3, down[2][2]=3, left[2][2]=3, right[2][2]=3. So arm length (excluding center) = min(3-1,3-1,3-1,3-1)=2. So L_max=2. So there exists a cross of arm length 1 and also arm length 2. Should we count both? The problem says "find the number of 'crosses' of 1s." If we have a cross with arms length 2, that's a cross. But also the same center with arms length 1 is also a cross? But is that cross distinct? It's a subset of the larger cross, but it's still a pattern of 1s in the grid: the cells that form a cross of length 1 are all 1, and they are exactly those 5 cells. Those cells are present. So why wouldn't that count as a cross? However, if we count all possible crosses, we might be double-counting: the large cross includes the small cross pattern, but they are separate patterns. Usually in such problems, they ask "how many crosses are there?" meaning how many plus signs can you find. Many similar problems: "Count the number of plus signs in a binary matrix" often define a plus sign as a 1 with equal arms length, and they count each such plus sign, even if overlapping. For instance, if you have a 3x3 all ones, the center gives a plus of size 1; the corners do not give pluses. That's one plus. If you have a cross shape of larger size, the same center gives multiple pluses? Typically they might count each plus sign regardless of size, as long as the arms are equal and at least length 1. For example, in a 5x5 cross (arms length 2), the center gives pluses of size 1 and 2. Are both counted? Let's check typical definitions: On LeetCode, "Largest Plus Sign" asks for the maximum order. But there is also a problem "Count the number of crosses in a binary matrix" maybe they want to count all crosses with any arm length. I'm not 100% sure.
Let's consider the wording: "You are given a 2D grid of integers. Write a function to find the number of "crosses" of 1s. A cross is a 1 with four arms of equal length." It says "a cross is a 1 with four arms of equal length." That describes a shape. It doesn't specify that the arms must be maximal. It doesn't say the cross has to be maximal. So any arrangement that fits that description is a cross. So if a cell has at least one 1 in each direction and the lengths of consecutive 1s in all four directions from that cell are at least some L, then for each possible L from 1 up to the minimal length, we have a cross of arm length L? But note: The arms are defined from that central 1. So if we have a configuration where there are at least L cells in each direction, then the cross of arm length L exists. Since the arms are equal length, we can set the arm length to L. So indeed, if minimal arm length (excluding center) is >=1, then there exists at least one cross. And if minimal arm length >=2, then there exist crosses of length 1 and 2? Wait careful: For a given center, doesn't the definition of a cross include the exact arm length? The cross shape includes the central cell and exactly L cells in each direction, not necessarily all the way to the boundary. If the grid has more than L cells in a direction, we can still have a cross of length L, because the pattern of 1s includes those cells; we don't require that the arms stop exactly after L; we just require that there are at least L consecutive 1s in each direction. But the cross shape for arm length L would be exactly the set: the central cell and the L cells in each direction. However, note: If there are more than L cells in a direction, then the cells beyond L are also 1s, but they are not part of the cross of length L? The cross shape is defined by its arms; if we consider a cross of length L, we consider only the cells up to distance L from center. Those cells are 1s because there is a longer streak. So that cross exists. So indeed, if the minimal possible arm length (the number of consecutive 1s in each direction, excluding center) is M, then there exist crosses of lengths 1,2,...,M at that center. So we would count M crosses for that center? That seems plausible if we want to count all crosses of all sizes. But then the total count would be sum over all centers of M. However, is that typical? Let's think: If we have a 3x3 block of all ones, center gives M=1 (since up=2, down=2, left=2, right=2 => M=1). So we would count 1 cross. That matches. For a larger cross with arm length 2, M=2, so we'd count 2 crosses at that center. That would give total 2 crosses. But does that make sense? The cross of length 2 includes the cross of length 1 as a sub-cross; they are distinct shapes because the arm lengths differ. Are they both "crosses"? According to definition, any 1 with four arms of equal length is a cross. The cross of length 1 uses only the immediate neighbors; those are all 1s, so it qualifies. So it should be counted. But is there any reason to exclude it? Possibly the problem intends to count the maximal cross at each center, i.e., each center contributes at most one cross (with arm length equal to the minimal arm length). But the phrase "number of crosses" could be ambiguous. However, often in grid pattern counting, each distinct pattern is counted once. If the pattern is defined by a set of cells that form a cross, then the cross of length 1 and the cross of length 2 are different sets of cells: the length 1 cross uses cells at distance 1, the length 2 uses cells at distance 2 as well. They are different sets, so they should be counted separately. But consider: the cross of length 2 includes the cross of length 1 as a subset, but it's a larger shape. It's a separate pattern; it's not the same cross. So both exist in the grid simultaneously because the grid contains all those 1s. But if you physically draw the shape of a cross of length 2, it draws the arms of length 2. If you draw the shape of length 1, it's a different shape (smaller). So the grid contains both shapes. However, if we count all shapes, we might get many. But is that what they intend? Many problems ask: "Count the number of crosses in a binary matrix." A cross is defined as a central 1 with arms of equal length. They might want to count each occurrence. For example, a problem on InterviewBit or GeeksforGeeks: "Count the number of crosses in a matrix." I recall similar: "Given a binary matrix, find the number of plus symbols." In some versions, they count each possible plus sign, and they might mention that overlapping plus signs are counted separately. For example, given a grid:
0 1 0
1 1 1
0 1 0
That's one plus (length 1). Given:
0 1 0
0 1 0
1 1 1
0 1 0
0 1 0
That's a plus of length 2? Actually that's a cross with arms length 2? Let's draw:
Row0: 0 1 0
Row1: 0 1 0
Row2: 1 1 1
Row3: 0 1 0
Row4: 0 1 0
That's a vertical line with a horizontal line at row2. That's not symmetric arms? It has left arm length 2? Actually center at (2,1): up: cells (1,1),(0,1) => length 2? But (0,1) is 1, (1,1) is 1, (2,1) center, down: (3,1),(4,1) => length 2. left: (2,0) is 1? Actually left from center: (2,0) is 1? The grid row2: 1 1 1, so (2,0) is 1, that's one left, but is there another left? (2,-1) out of bounds. So left arm length =1. right: (2,2) is 1, then (2,3) out of bounds, so length 1. So arms not equal. So not a cross. So for cross we need equal lengths in all four directions. So for a cross of length 2, we need 2 cells in each direction. So the cross is symmetric. So the minimal cross that is larger than 1 is like a bigger plus.
Thus, for a given center, the maximum possible cross arm length is M = min(up[i][j]-1, down[i][j]-1, left[i][j]-1, right[i][j]-1). If M >= 1, then there exists at least one cross (with some arm length). But the question: Do we count the number of centers that have at least one cross? Or do we count the total number of crosses of all possible arm lengths? The phrasing "number of 'crosses' of 1s" might mean count each cross shape. If we treat each cross as a distinct occurrence, then for a given center with M >= 1, we would count M crosses (one for each possible arm length from 1 to M). But is that typical? Let's see: If we have a large cross, we could also consider that it's one cross, but the cross is defined by its size. So if the grid has a cross of size 2, it's still a cross. But also it contains a cross of size 1 as a sub-pattern. However, many pattern counting problems would count both, because they are separate patterns. However, sometimes they specifically say "maximal cross" or "largest cross". Here they didn't say maximal. They just said "a cross is a 1 with four arms of equal length." So that description fits both size 1 and size 2. So both are crosses.
But maybe they intend that the arms are exactly the points from the center until a 0 or boundary. That would be the maximal cross. In that case, for a given center, there is at most one cross (the maximal one). But the phrase "with four arms of equal length" doesn't imply maximal; it just says the arms have equal length. Could be any length as long as all arms are equal. So we need to deduce from typical problem sets. I recall a problem: "Count the number of crosses in a matrix" on GeeksforGeeks. Let's search memory: I think there is a problem "Count the number of crosses formed by 1s in a binary matrix" where a cross is defined as a 1 with arms of equal length. I think I've seen a solution where they compute the number of consecutive 1s in four directions for each cell, then for each cell, they compute the minimum of those four values (maybe including the cell? They often compute left, right, up, down counts that include the cell. Then the order = min(left, right, up, down). If order > 1? Or order >= 1? Actually if order is the number of consecutive 1s including the center, then the arm length is order-1. They might count each cell that has order >= 2 as a cross? But then each cell would count as one cross, but that cross would be the maximal cross at that center? If order = 3, that means there are at least 2 cells in each direction, so you could have a cross of arm length 1 and 2. But if we count only the maximal cross, then we count 1 per center. That seems plausible: count each cell that can serve as the center of a cross of some size. But they might also count the actual shape, but the shape is uniquely defined by its center and arm length. If we only consider the maximal arm length, we might be missing smaller crosses which have the same center but are also valid crosses. However, are those smaller crosses considered distinct crosses? They have the same center but different arm lengths. Could there be two crosses with the same center? Possibly yes. For example, if you have a cross of arm length 3, then the pattern of a cross of arm length 2 is also present, but it's a subset. But if you are asked "how many crosses are there?" and you see a big plus, you would probably say there is one plus. You wouldn't say there are three pluses (sizes 1,2,3) because they all coincide. Usually a plus sign is defined by its center and its size; if you have a large plus, it's still just one plus sign; but the definition might be that a plus sign of size k is a specific set of cells; if the grid has more cells, it might still contain a plus sign of size k, but also of size smaller? But the plus sign of size k is a pattern: a central 1 and exactly k cells in each direction (i.e., distance k). If the grid has a plus sign of size 3, then it automatically contains the plus sign of size 2? Actually, does it contain the plus sign of size 2 as a set of cells? The set for size 2 is {center + cells at distance 1 and 2? Wait: plus sign of size k typically includes all cells from distance 0 to k along the axes. That is, it includes the cells at distance 1 and distance 2? Let's be precise: If we say a plus sign of arm length k (order k) consists of the central cell and all cells that are in the same row or column within Manhattan distance k? Actually the arms are lines: the cells that are in the same row to the left and right up to k steps, and in the same column up and down up to k steps. That includes all intermediate cells. So a plus of order 3 includes cells at distances 1,2,3 along the arms. That set includes the plus of order 2? The plus of order 2 would consist of cells at distances 1 and 2 (and center). That set is a subset of the order 3 plus. So indeed, if a grid contains a plus of order 3, it also contains a plus of order 2 (by ignoring the outermost cells). But is that considered a distinct plus? If you are asked to count pluses, you might count each distinct plus pattern that appears. Since the pattern of order 2 is also present (the cells for order 2 are all 1), you could say there is a plus of order 2. But then the grid would contain multiple pluses that overlap heavily. Usually, when counting patterns in a grid, we consider each possible pattern that can be formed by the cells, regardless of whether they are subsets of larger patterns. So indeed, you could have many overlapping pluses. For example, in an all-1 grid of size N x M, many centers can have many pluses. But if you count all pluses of all sizes, the count could be huge (O(Nmin(N,M))). That might be intended if they want to count all possible crosses. But is that feasible for large grids? The problem statement doesn't give constraints. Usually they want an efficient solution. If we need to sum over all centers the maximum arm length (because that's the number of crosses at that center: cross lengths from 1 to M), then the answer is sum_{i,j} max(0, M_ij). That can be computed by DP and summing. That would be O(NM). Both are fine. Which one is more likely? Let's parse: "find the number of 'crosses' of s." The word 'crosses' plural. It could be interpreted as count the distinct cross shapes. But then if you have a large cross, you could argue there is only one cross shape (the largest) because the smaller ones are not full crosses if the arms must be exactly equal length and must terminate at the boundary of the cross? Actually, if we have a large cross, the cells that form a smaller cross are still there, but does that smaller cross also have arms of equal length? Yes. So it is a cross. So it would be counted separately. But is there any example where we would count more than one cross per center? If the grid is all 1s, for a 5x5 all-1 grid, for the center (2,2): up[2][2]=3, down=3, left=3, right=3 => M=2 (since -1). So crosses of length 1 and 2 exist. Also, could there be cross of length 0? No. So center contributes 2 crosses. For other cells, maybe they also contribute? For example, cell (1,2): up=2, down=2, left? left[1][2]: row1 all ones? In all-1 grid, left[1][2]=3, right[1][2]=? Actually row1: left[1][0]=1, left[1][1]=2, left[1][2]=3; right[1][2]=3? Right from right: right[1][4]=1, right[1][3]=2, right[1][2]=3. So up[1][2]=2, down[1][2]=3? Wait down from bottom: down[4][2]=1, down[3][2]=2, down[2][2]=3, down[1][2]=4? Actually if grid all ones, down[i][j] counts consecutive ones downward including current: so down[4][j]=1, down[3][j]=2, down[2][j]=3, down[1][j]=4, down[0][j]=5. Similarly up[1][2]=2 (since up[0][2]=1, up[1][2]=2). So min(2-1=1, 4-1=3, left[1][2]-1=2, right[1][2]-1=2) = min(1,3,2,2)=1. So M=1, so cell (1,2) also contributes 1 cross. So total crosses would be many: sum over all cells of M. In a 5x5 all-ones, compute M for each cell? Let's compute approximate: For each cell, the arm lengths are determined by distance to edges. The maximal arm length for a cell (i,j) (0-indexed) is limited by min(i, n-1-i, j, m-1-j). Actually the number of consecutive 1s in each direction including center is distance to border +1? In all-ones grid, up[i][j] = i+1, down[i][j] = n-i, left[i][j] = j+1, right[i][j] = m-j. Then M = min(i+1, n-i, j+1, m-j) - 1. That's the minimal of distances to edges? Actually up-n? up includes center: up = i+1, so up-1 = i. down-1 = n-1-i. left-1 = j. right-1 = m-1-j. So M = min(i, n-1-i, j, m-1-j). That's the Chebyshev distance to the nearest border? Actually it's the Manhattan? It's the minimum of the distances to the four edges (i distance to top, n-1-i to bottom, j to left, m-1-j to right). So M is the number of cells in each direction you can extend from the center while staying within the grid. So for a 5x5 grid (n=5,m=5): For center (2,2): min(2,2,2,2)=2 => M=2. For (1,2): min(1,3,2,2)=1 => M=1. For (0,2): min(0,4,2,2)=0 => M=0 (not cross). So total crosses = sum_{i,j} max(0, M). This sum can be large, roughly O(nmin(n,m))? Actually it's like sum of min distances. In a square n x n, it's sum over i,j of min(i, n-1-i, j, n-1-j). That's O(n^3)? Actually number of cells with M >= k is about (n-2k)*(n-2k) for k from 0 to floor((n-1)/2). So total sum of M is sum_{k>=1} count(cells with M >= k). That's about sum_{k=1}^{n/2} (n-2k)^2 ~ O(n^3). So in worst-case all-ones grid, the total number of crosses (if counting all sizes) would be O(n^3) which could be up to ~10^9 for n=1000? That's huge but maybe not feasible to enumerate individually, but we only need the count, which could be computed in O(n^2) by summing M. That's fine; M can be large but sum fits in integer? For n=1000, sum is about (n^3)/12 ~ 8e10, which fits in 64-bit. So it's okay. But the problem doesn't specify constraints, so both interpretations are possible.
Let's check typical LeetCode problems: There's "Count Number of Nice Subarrays", etc. Not relevant. There's "Number of Submatrices That Sum to Target". Not that. There's "Number of Crosses in a Grid"? I'm not sure. I recall a problem on HackerRank: "Crosses" maybe in a competition. Possibly they want to count each cross shape defined by its center and arm length. But it's ambiguous.
Let's read the exact phrasing: "You are given a 2D grid of integers. Write a function to find the number of "crosses" of 1s. A cross is a 1 with four arms of equal length. Please write a function that solves this problem, and explain your algorithm."
It says "A cross is a 1 with four arms of equal length." It doesn't say "maximal". So any such configuration qualifies. I think it's more natural to count each distinct cross, i.e., each center and each possible arm length such that the arms are equal and at least length 1. But maybe they mean count the number of positions that are centers of such crosses. Because they say "a cross is a 1 with four arms". So if you have a 1 that has four arms (any equal length), it is a cross. So each such 1 is a cross. That interpretation would count each cell that can be the center of at least one cross as one cross. That is simpler: count cells where min(up[i][j], down[i][j], left[i][j], right[i][j]) >= 2? Because we need at least one cell in each direction, meaning each direction has at least 2 consecutive 1s including the center. So condition: up[i][j] >= 2, down[i][j] >= 2, left[i][j] >= 2, right[i][j] >= 2. That's it. So the answer is the number of cells satisfying that. That is a common problem: "Count the number of plus signs" where the plus sign is of size at least 1. Many problems ask exactly that: "Given a binary matrix, count the number of plus signs." For example, on GeeksforGeeks: "Count the number of plus signs in a binary matrix" where a plus sign is defined as a 1 with all 1s in its four directions. That problem counts each cell that can be the center of a plus sign (with arms at least length 1). Indeed, I recall a GFG problem: "Count the number of crosses in a matrix" maybe it's that. Let me search memory: There is a GFG article "Count number of crosses in a matrix" where they define cross as a cell with 1 and with all adjacent cells in all four directions also 1? Actually that would be arms of length 1 only. But they might require arms of equal length, but the simplest is length 1. However, they might allow longer arms. Actually I've seen: "Count the number of plus signs in a matrix" where you need to check that in all four directions, there is at least one 1. That's minimal plus. But they might also require that the arms are of equal length? That would be more strict: you need the distances to the next zero or boundary in all four directions to be equal. That is different: for a cell to be a cross, the number of consecutive 1s in each direction (including the center?) must be equal? Or at least the arms must be of equal length. If we require equal lengths, then we need up_len_excluding_center = down_len_excluding_center = left_len_excluding_center = right_len_excluding_center? Or at least they can be chosen to be equal, meaning the minimal among them is the maximum equal length possible. But if we require that the arms are of equal length, we need the actual lengths of the arms (the streak lengths) to be exactly some L. If the streaks are longer in some directions, we can still choose L as the minimal, but then the actual arms of the cross would be exactly L cells; the extra longer streaks are not part of the cross shape. So the condition for a cross to exist is that the minimal of the four arm lengths (excluding center) is at least 1. That is exactly the same condition as for a plus sign of size 1? Wait no: for a cross of any size, we only need that there is some L >=1 such that each direction has at least L cells. That's equivalent to min_arm_length >= 1. That's the same condition as requiring each direction to have at least 1 cell (i.e., immediate neighbor 1). So if a cell has up_strlen_excluding >=1, down >=1, left >=1, right >=1, then there is at least a cross of length 1. But if the arm lengths are not equal? Actually they don't need to be equal initially; we can choose L = the minimum of them. That will be the largest possible equal arm length, and that cross of length L exists. So condition for existence of any cross is simply that all four immediate neighbors are 1. That is a much simpler condition. However, the problem explicitly says "four arms of equal length." If we just check immediate neighbors, then the arms have length 1 each, so they are equal. So the minimal cross requires immediate neighbors. If a cell has up=2, down=3, left=2, right=4, then the minimal arm length is 2? Actually excluding center: up_len_excluding = up-1 = 1? Wait careful: if up[i][j] includes center and counts consecutive ones upward. For immediate neighbor up to be 1, we need up[i][j] >= 2. So condition for at least length 1: up[i][j] >= 2, down[i][j] >= 2, left[i][j] >= 2, right[i][j] >= 2. That's it. So many cells might satisfy that. But if a cell has up=3, down=2, left=2, right=2, then minimal arm length excluding center = min(2,1,1,1)? Wait compute: up[i][j] = 3 => up_excluding = 2; down[i][j] = 2 => down_excluding = 1; left=2 => left_excluding=1; right=2 => right_excluding=1. So minimal = 1. So there exists a cross of length 1. But does there exist a cross of length 2? No because down_excluding only 1. So only length 1. So condition for any cross is that each direction has at least one cell beyond center, i.e., each of up, down, left, right >=2. That is exactly the condition for a plus sign of size 1. So the cross of length 1 is essentially a plus sign where each arm length is exactly 1. But note: if a cell has up=5, down=5, left=5, right=5, then there exist crosses of lengths 1,2,3,4. So each of those are valid crosses. The condition for existence of any cross (including length 1) is the same: immediate neighbors all 1. So if we only count centers that have at least length 1, we would count each center once, regardless of whether it also supports longer crosses. But then we wouldn't differentiate the longer crosses. The problem says "find the number of crosses". If we have a center that supports multiple crosses (different arm lengths), should we count each cross separately or just once? The phrase "a cross is a 1 with four arms of equal length." The central 1 is part of the cross. The cross is defined by the central 1 and the arms. If a single central 1 has arms of equal length L=1, that's a cross. If that same central 1 also has arms of equal length L=2, that's a different cross (larger). But are they both "a 1 with four arms of equal length"? The central 1 is the same, but the arms are different sets of cells. The description "a cross is a 1 with four arms of equal length" could be interpreted as: we look at a 1 and we look at the lengths of its four arms (the runs of consecutive 1s in each direction). For that 1 to be a cross, the lengths of those runs must be equal. But if the runs are unequal, it's not a cross. However, the runs themselves have specific lengths. If the runs are up=5, down=5, left=5, right=5, then the lengths are all 5, so they are equal. That means the central 1 has arms of length 5 (up to the boundary). So does that central 1 then qualify as a cross? Yes, because its arms are of length 5 (the actual length of the runs). But if we talk about arms, do we consider the entire run or can we truncate? The natural interpretation: the arms are the consecutive 1s extending from the center until a 0 or boundary. So the arm length is defined by the maximum possible length. So for a given center, there is a specific arm length in each direction (the maximal). Those four lengths might or might not be equal. If they are equal, then that center is a cross (with that equal arm length). If they are not equal, then it's not a cross, even though you could choose a smaller L that is <= all four, but the arms are defined by the actual data; they are not truncated arbitrarily. The phrase "a cross is a 1 with four arms of equal length" suggests we look at the actual arms in the grid, not a subset. In other words, from that 1, you look in each direction along the grid until you hit a 0 or the edge; the number of 1s you encounter in each direction (including maybe the center? Usually arms start from the center and go out; the length of the arm is the number of cells from the center outward until a non-1 is encountered? Or maybe excluding the center? They might say "arms" meaning the cells other than the center. Typically, in a plus sign, the arms are the cells extending from the center. So the arm length is the number of cells in that direction (excluding the center). So for a given center, we can compute the length of each arm as the count of consecutive 1s in that direction starting from the cell adjacent to the center and moving outward until a 0 or boundary. That's a fixed value for that center. If those four lengths are equal, then the center is a cross. So that's a binary condition: either equal or not. There is no concept of a cross of arm length L less than the maximal unless we consider that the arms might be truncated by 0s? Actually if there is a longer streak, the arm length is the full streak. You cannot say the arm length is 2 if there are actually 3 cells, because then the arm would be length 3. The arm is defined by the consecutive 1s from the center outward; if there is a 1 at distance 3, then the arm length is at least 3. So the actual arm length is the number of consecutive 1s until a non-1. So it's a fixed number. So for a center, the arm lengths are predetermined. If they happen to be equal, it's a cross. If they are not equal, it's not a cross. So we would count each center that has equal arm lengths (including possibly zero? But must be at least 1? If a cell has no 1s in any direction, arms length 0, then all equal (0) but that's trivial? Usually a cross requires arms of positive length. So we need each arm length >= 1 and they are equal. That means each direction must have at least one 1, and the counts must be equal.
But wait: What about the scenario where a cell has up=2, down=2, left=2, right=2? Then arm lengths (excluding center) are up_excl = 1, down_excl =1, left_excl=1, right_excl=1. They are equal. So it's a cross of arm length 1. The actual up length (including center?) is 2. So it's consistent.
What if up=3, down=2, left=3, right=3? Then arm lengths: up_excl=2, down_excl=1, left_excl=2, right_excl=2. They are not equal. So not a cross. However, could we consider a cross of arm length 1? Because up_excl>=1, down_excl>=1, left_excl>=1, right_excl>=1? Yes, but the actual arms as defined by the grid are not equal because down arm is only length 1 while others are longer. The definition "four arms of equal length" means the actual arms emitted from that center must be equal. It doesn't say "there exists some L such that each direction has at least L consecutive 1s". It says "a cross is a 1 with four arms of equal length." In the grid, the arms are the stretches of 1s. The lengths of those stretches are what they are. So if they are not equal, it's not a cross. So the condition is: up_excl = down_excl = left_excl = right_excl >= 1.
But is it possible that up_excl = down_excl = left_excl = right_excl but there are also extra 1s beyond? If up_excl = 2, but there is a 1 at distance 3? That would mean up_excl should be at least 3, because arm length is the count until a non-1. So if there is a 1 at distance 3, then the arm length is at least 3. So up_excl would be the total number of consecutive 1s in that direction. So if we have a longer streak, the arm length is that longer value. So we cannot arbitrarily set it to a smaller value. So the equality must hold for the actual full arm lengths. So center is a cross if and only if the four directional lengths (excluding center) are all equal and >=1.
Thus the condition is: For cell (i,j) with grid[i][j]==1, let up_len = number of consecutive 1s directly above (i,j) (i.e., in positions (i-1,j), (i-2,j), ... until a 0 or boundary). Similarly down_len, left_len, right_len. Then if up_len == down_len == left_len == right_len >= 1, then (i,j) is a cross.
Now, what about the case where arms lengths are 0? If all four are 0, then the cell is isolated, but then arms length =0, but is that considered a cross? Usually not, because arms must have some length. So require >=1.
Thus we need to compute for each cell the four directional lengths (excluding center). Then check if they are all equal and positive. Count such cells.
But is it possible that a cell is counted as a cross even if the arms are of length 0? They said "arms of equal length", arms could be length 0? Probably not, because then it's just a single 1, not a cross. So require >0.
Now, is there any nuance about arms overlapping? Not needed.
So algorithm: Precompute four DP arrays: up, down, left, right. But careful: We want lengths excluding the center. So we can compute inclusive counts and then subtract 1. Define:
- up_incl[i][j] = if grid[i][j]==1 then (if i>0 then up_incl[i-1][j] + 1 else 1) else 0.
- down_incl[i][j] = if grid[i][j]==1 then (if i < n-1 then down_incl[i+1][j] + 1 else 1) else 0. But we can compute from bottom-up.
- left_incl[i][j] = if grid[i][j]==1 then (if j>0 then left_incl[i][j-1] + 1 else 1) else 0.
- right_incl[i][j] = if grid[i][j]==1 then (if j < m-1 then right_incl[i][j+1] + 1 else 1) else 0.
Then for cell (i,j) that is 1, compute:
up_len = up_incl[i][j] - 1 (if we count center in up_incl; actually up_incl includes the current cell. So the number of cells above including current? Actually up_incl[i][j] is the number of consecutive 1s ending at (i,j) from above, meaning it includes (i,j) and all above until a non-1. So the number of cells above (i,j) (excluding (i,j)) is up_incl[i][j] - 1. Similarly down_incl[i][j] includes (i,j) and below, so down_excl = down_incl[i][j] - 1. Similarly left_excl = left_incl[i][j] - 1, right_excl = right_incl[i][j] - 1.
Then check if all four excl lengths are equal and >= 1. So condition: up_len == down_len == left_len == right_len && up_len >= 1.
Alternatively, we could compute excl lengths directly by starting from neighbor cells.
But note: For down_incl, if we compute from top to bottom, we'd need to do bottom-up. So we'll compute four passes.
Complexity: O(nm) time, O(nm) space (or we can reuse some). But we need all four values for each cell to compare. So we can store four 2D arrays or compute two at a time.
But careful: For down_incl, we need to traverse from bottom to top. So we can compute:
for i from n-1 down to 0:
for j from 0 to m-1:
if grid[i][j]==1:
down_incl[i][j] = (if i < n-1 then down_incl[i+1][j] + 1 else 1)
else down_incl[i][j]=0
Similarly for right: for each row, from right to left.
So that's fine.
Then second pass to count.
Edge cases: If grid empty, return 0.
Now, what about the interpretation where we count only centers that have at least arm length 1 (i.e., immediate neighbors all 1)? That condition is simply up_incl[i][j] >= 2, down_incl[i][j] >= 2, left_incl[i][j] >= 2, right_incl[i][j] >= 2. That's a simpler condition, but does not require equality of arm lengths beyond that? Actually that condition ensures each direction has at least one cell after center, but doesn't require equality. But if we require equality of the full arm lengths, we need up_incl[i][j] == down_incl[i][j] == left_incl[i][j] == right_incl[i][j] (and >=2). That is a stricter condition. Which one makes sense? The phrase "four arms of equal length" suggests equality. So we need lengths equal.
Thus we must check equality of the full arm lengths (the maximum consecutive ones). That seems plausible.
But let's test with some examples:
Example 1:
grid = [
[1,0,1],
[0,1,0],
[1,0,1]
]
This looks like an X, not a cross. Center (1,1) is 1. up: above center is 0, so up_len=0; down=0; left=0; right=0. Not cross.
Example 2:
grid = [
[0,1,0],
[1,1,1],
[0,1,0]
]
This is a plus of size 1. For center (1,1): up_incl[1][1] =? row0 col1 is 1, row1 col1 is 1 => up_incl[1][1] = up_incl[0][1] + 1. up_incl[0][1] = 1 (since top row). So up_incl[1][1]=2. down_incl[1][1]: compute from bottom: row2 col1=1, row1 col1=1 => down_incl[1][1] = down_incl[2][1]+1. down_incl[2][1]=1, so down_incl=2. left_incl[1][1]: left: (1,0)=1 => left_incl[1][0]=1, then left_incl[1][1]=2. right_incl[1][1]=2. So all incl =2, excl=1, equal. So cross. Count=1.
Example 3:
grid = [
[0,1,0],
[0,1,0],
[1,1,1],
[0,1,0],
[0,1,0]
]
As earlier, not a cross because left and right arms lengths are 1? Actually let's compute center at (2,1). up: rows 1,0? (1,1) is 1, (0,1) is 1? Actually row0 col1=0? The grid: row0:0,1,0; row1:0,1,0; row2:1,1,1; row3:0,1,0; row4:0,1,0. So row0 col1=1? Wait row0: [0,1,0] => col1 is 1. So (0,1)=1. (1,1)=1. (2,1)=1. So up_incl[2][1] =? up from top: row0 col1=1, row1 col1=1, row2 col1=1. So up_incl[2][1]=3? Actually compute: up_incl[0][1]=1. up_incl[1][1]= up_incl[0][1]+1=2. up_incl[2][1]= up_incl[1][1]+1=3. down_incl[2][1]: bottom: row4 col1=1, row3 col1=1, row2 col1=1 => down_incl[2][1]=3? Actually down_incl from bottom: down_incl[4][1]=1, down_incl[3][1]=2, down_incl[2][1]=3. left_incl[2][1]: left: (2,0)=1, (2,1)=1 => left_incl[2][0]=1, left_incl[2][1]=2. right_incl[2][1]: right: (2,2)=1, so right_incl[2][2]=1, right_incl[2][1]=2. So inclusives: up=3, down=3, left=2, right=2. So excl lengths: up_excl=2, down_excl=2, left_excl=1, right_excl=1. Not equal. So not a cross. So that's correct.
Example 4: a larger cross with all four arms equal: like a proper cross shape.
grid = [
0,0,1,0,0
0,0,1,0,0
1,1,1,1,1
0,0,1,0,0
0,0,1,0,0
]
center at (2,2). Compute: up_incl: row0 col2=1, row1 col2=1, row2 col2=1 => up_incl[2][2]=3? Actually up_incl[0][2]=1; up_incl[1][2]=2; up_incl[2][2]=3. down: row2-> row3 row4: down_incl[4][2]=1; down_incl[3][2]=2; down_incl[2][2]=3. left: row2 col0=1, col1=1, col2=1 => left_incl[2][0]=1; left_incl[2][1]=2; left_incl[2][2]=3. right: row2 col4=1, col3=1, col2=1 => right_incl[2][4]=1; right_incl[2][3]=2; right_incl[2][2]=3. So all incl=3, excl=2, equal. So cross. Count=1.
What about a bigger cross: all ones in a 7x7 cross? That would have equal arms. So only the center counts as one cross, even though the arms may be length 3. So that seems plausible: each cross is identified by its center. So the number of crosses is the number of cells that are the center of a cross.
But wait: Could there be multiple crosses with different centers overlapping? Yes, that's fine.
Now, is there any scenario where a cell qualifies as a cross but also could be considered as part of other crosses? That's fine.
Thus the interpretation that a cross is defined by a central 1 and the lengths of its four arms (the maximal runs) being equal and at least 1 yields a count of centers satisfying that.
Now, what about the case where the arm length is zero? That would be a single 1 with no arms; not a cross.
Thus algorithm: compute directional consecutive ones inclusive, then for each cell that is 1, compute arm lengths excl = incl-1. Check if all four excl are equal and >0. Count.
That's O(nm) time, O(nm) space. We can possibly reduce space to O(n*m) anyway.
But maybe we can compute on the fly? We need up_incl, down_incl, left_incl, right_incl. We can compute up and left in one pass (top-left to bottom-right) and down and right in another pass (bottom-right to top-left). Then store them. Or we can compute all four and then check. It's fine.
Now, could there be alternative interpretation: count each cross shape (center+arm length) if the maximal arms are equal? That's the same as counting centers where up_excl == down_excl == left_excl == right_excl, and that common value is the arm length. That's still one per center. So it's essentially the same as counting centers with equal arm lengths.
But wait: If the arms are equal but not maximal? For example, suppose up_incl=4, down_incl=4, left_incl=3, right_incl=3. Then excl: up=3, down=3, left=2, right=2. They are not equal. So no cross. But could we consider a cross of arm length 2? That would require up>=3, down>=3, left>=3, right>=3? Actually for arm length L, we need each direction to have at least L cells after center. So if L=2, we need up_excl>=2, down_excl>=2, left_excl>=2, right_excl>=2. Here up_excl=3, down=3, left=2, right=2 => all >=2, so a cross of length 2 exists? But are the arm lengths defined as exactly L? The arms we would consider for such a cross would be exactly the first L cells in each direction. However, the grid has longer arms in up/down. Does that matter? The cross of length 2 would use only the first 2 cells up and down and left and right. Those cells are all 1s. So that pattern exists. But the definition of a cross: "a 1 with four arms of equal length." It doesn't say the arms must be maximal. So we could select L=2 and consider that cross. But is the central cell considered to have arms of length 2? In the grid, the arms are actually longer than 2. But we can define a cross as a subgrid where the central cell and exactly L cells in each direction are all 1s. That is a valid cross shape. So if the grid has longer arms, it still contains a cross of length L. So we could count it. However, if we are counting crosses, we might count each such L separately for that center. So that would lead to multiple crosses per center.
So the debate: Does the cross definition refer to the maximal arms or any possible equal arms? Typically, when we talk about a pattern in a grid, we say "there is a plus sign of size k" if there is a central cell with k consecutive 1s in all four directions. If there are more than k, we still say there is a plus sign of size k (and also of size k+1 etc). In the "Largest Plus Sign" problem, they compute the maximum k for each cell, but they are interested in the maximum. However, if they ask "count the number of plus signs", I think they usually count each plus sign individually, meaning for each cell and each possible k (>=1) such that the cell has at least k in each direction, you count one plus sign. I've seen a problem: "Given a binary matrix, count the number of plus signs." And the solution often is: for each cell, find the minimum of the four directional counts (including center). Then the number of plus signs centered at that cell is that minimum (or maybe min-1?). Actually if inclusive counts are L_up, L_down, L_left, L_right (including center), then the maximum arm length (excluding center) is min(L_up, L_down, L_left, L_right) - 1. The number of plus signs centered at that cell is that max arm length (since you can have plus signs of lengths 1,2,..., max). But some solutions might just check if min >=2 to count at least one plus. I need to recall. Let's search memory: There's a known problem: "Count the number of pluses in a binary matrix." I think I've seen it in Codeforces or HackerRank. Possibly the answer is sum over all cells of (min_val - 1) where min_val = min(up, down, left, right) and we take max(0, min_val - 1). Because each cell contributes (max arm length) plus signs. That would count all plus signs of all sizes. That seems like a plausible problem: they ask "find the number of crosses", meaning total count.
But which one is more likely? Let's examine wording: "Write a function to find the number of 'crosses' of 1s." If they meant to count distinct cross shapes, they might have said "count the number of positions that are centers of crosses" or "count cells that are centers of crosses". They used "crosses" which might imply the shapes. However, a shape is defined by its center and size. So we need to count each shape. Usually, if they wanted to count each center once, they'd say "count the number of cells that are the center of a cross" or "count the number of crosses (i.e., plus signs) present". But I'm leaning towards the interpretation that we count each cross shape, not just each center that can be a cross. Why? Because they specifically say "A cross is a 1 with four arms of equal length." That describes a specific cross with a particular arm length. So if a cell has longer arms, it also has crosses of smaller lengths, but those are different crosses because they have different arm lengths. So they would be counted separately. However, is it natural to say that a grid contains multiple crosses if there's a big cross? You could argue that the grid contains exactly one cross: the big plus. But if you look at the grid, you can see a smaller plus within it as well. But do we consider that as a separate cross? Typically, when we talk about patterns in a grid, we count occurrences of the pattern. For example, in a grid of all 1s, how many subgrids of size 2x2 of all 1s? Many. But here the pattern is not a subgrid but a cross shape. So the number of such patterns could be many. I recall a problem: "Count the number of crosses in a matrix" from GFG: I think the solution they gave was to compute four matrices and then for each cell compute the minimum of the four values (which are inclusive counts) and then add (min-1) to the answer. Let me check memory: On GFG there is an article "Count the number of crosses in a matrix" where they define cross as a 1 with arms of equal length. I think they compute left, right, up, down arrays, then for each cell they find min of these four values. Then if min > 1, they add min-1 to answer (since the number of crosses centered at that cell is min-1). That sums over all cells. I'm trying to recall. I'll try to search mental memory: I think I've seen a problem: "Count of crosses formed by 1's in a binary matrix" where they said a cross is formed if there exists a center with arms of equal length, and the cross of size k is counted as 1 cross. But they might also say "size of cross is min of the arms lengths". And they sum contributions. I'm not entirely sure.
Let's consider an example to see which interpretation yields a typical answer. Suppose we have a cross of arm length 2 (as earlier). Under the "center only" interpretation, answer = 1. Under the "sum of max arm lengths" interpretation, answer = 2 (since that center contributes 2 crosses). Which one is more intuitive? If I were given that grid, I'd probably say there is one cross (plus sign) of size 2. I wouldn't say there are two crosses because there's also a size 1 cross inside; that size 1 cross is not a distinct shape? Actually it is a shape, but it's completely contained within the larger cross. But if you're asked to count all crosses, you might count both because they are both valid plus signs. However, in many such problems, they explicitly ask for the number of plus signs of size at least 1, meaning any plus sign, and they count all, leading to sum of min-1. For example, in the problem "Number of Plus Signs in a Binary Matrix" on LeetCode? I'm not aware. But there is a known technique: precompute four directions and then the number of plus signs at each cell is min(up, down, left, right) - 1. And total count is sum over cells. I think I've seen that.
Let's try to find a reference. There's a LeetCode problem "Largest Plus Sign" which asks for the maximum order. There's also a problem "Count Submatrices With All Ones" which is different. Not this.
Maybe we can search memory of HackerRank: "Crosses" in a grid? Not sure.
Let's think: If they wanted to count each cell that can be a center, they'd likely say "count the number of cells that are the center of a cross" or "count the number of crosses where each cross is defined by its center". They didn't. They said "find the number of 'crosses' of 1s." That seems like counting the patterns themselves.
Consider a small example:
grid:
1 1 1
1 1 1
1 1 1
All 1s. How many crosses? If we count each center that has equal arm lengths? Let's compute for each cell:
- Corners: (0,0): up=1, down=3, left=1, right=3. Not equal (1 vs 3). So not cross.
- Edge centers: (0,1): up=1, down=3, left=2, right=2. Not equal (1 vs 2). So not cross.
- (1,0): similar.
- Center (1,1): up=2, down=2, left=2, right=2 => equal, cross (arm length 1).
- (1,2): similar to edge.
- etc.
Also (2,2) corner no. So only the center? Actually also (1,1) only? But what about (0,0) no. So total crosses = 1 if counting centers. But if counting all plus signs of any size, we also have crosses of arm length 1 at other cells? Let's compute for (1,1) we have max arm length=1 (since up=2, down=2, left=2, right=2 => max arm length=1). So (1,1) contributes 1 cross. Others contribute 0. So total =1. So both interpretations yield 1 here.
Now consider a 5x5 all-1 grid. Using "centers only" (equal arms condition) we need to find cells where up_incl, down_incl, left_incl, right_incl are all equal (since arm lengths must equal). That would require that the distances to the edges are symmetric: i must equal n-1-i, and j must equal m-1-j. That means i = (n-1)/2 and j = (m-1)/2 only if n and m odd. So only the exact center cell(s) could have symmetric distances. For a 5x5, center (2,2) has distances: up=3, down=3, left=3, right=3. Actually up_incl = 3? For center (2,2): up_incl = number of consecutive ones from top to that row inclusive = i+1 = 3. down_incl = n-i = 3? n=5, i=2 => down_incl = 5-2 =3. left_incl = j+1 =3, right_incl = m-j = 5-2=3. So equal. So (2,2) qualifies. What about cell (1,2)? up_incl = i+1 =2, down_incl = n-i =4, left_incl = j+1 =3, right_incl = m-j =3. Not equal. So not cross. Similarly (2,1): up=3, down=3, left=2, right=4? Actually left_incl = j+1 =2, right_incl = m-j =5-1=4. So not equal. So only the center cell qualifies. So total crosses =1 under center-only interpretation. But what about cross of size 1? The center cell also has arms of length 1, but also arms of length 2? Actually its arm lengths: up_excl = up_incl-1 = 2, down=2, left=2, right=2. So arm lengths are 2? Wait up_excl = 2? up_incl=3 => up_excl=2. That means the arm extends two cells up: (1,2) and (0,2). So the cross with arm length 2. So that's the maximal cross. But are there any other crosses? Could there be a cross of arm length 1 centered at (2,2)? The arms for that would be only immediate neighbors: (1,2),(3,2),(2,1),(2,3). Those are 1s. So that pattern exists. But is it considered a separate cross? If we consider the actual arms of the cell, they are length 2, not 1. So the cell's arms are of length 2, so the cross at that cell has arms length 2. The existence of a cross of length 1 is not defined by the actual arm lengths of the central cell; it's defined by a subset of the cells. But does a cross of length 1 have the same center? Yes, it would also be centered at (2,2). But the cross of length 1 would have arms of length 1. However, the grid at (2,2) has arms of length 2. That doesn't mean that there is no cross of length 1; it means that the central cell's arms are longer, but if we consider the cross of length 1, we are effectively taking a subset of the arms. But is that considered a distinct cross? Typically, when we talk about a cross pattern, we refer to the entire shape as defined by its arms. If a cell has a longer arm, we could still say that there is a cross of length 1 contained within it, but that cross is not "centered" at (2,2) with arms of length 1 because the arms are longer; but we can still define a cross as any set of cells that satisfy the pattern. That set is exactly the cells of a cross of length 1. So it's present. So there are two crosses centered at (2,2): one with arm length 1 and one with arm length 2. But if we count them separately, total crosses = 2. However, in a 5x5 all-ones grid, could there be crosses centered elsewhere? Possibly other cells have equal arm lengths? For a cell like (2,1): up_incl =3, down=3, left_incl=2, right_incl=4. Not equal. So not a cross for any arm length? Wait, could there be a cross of arm length 1 at (2,1)? For arm length 1, we need left_excl >=1, right_excl >=1, up_excl >=1, down_excl >=1. For (2,1): left_excl = left_incl-1 =1, right_excl= right_incl-1 =3? Actually right_incl=4 => right_excl=3. So they are not equal, so it's not a cross because the arms lengths are not equal. For arm length 1, we need the actual arms we use to be equal. If we choose to use only the first cell to the left and the first cell to the right, they are both 1s. But the arm lengths we consider are the lengths of the arms in the cross shape. If we define a cross of arm length 1, we require that the arm in each direction consists of exactly one cell. That cell must be 1. It doesn't matter what lies beyond; we only care about the cell at distance 1. But the definition "a 1 with four arms of equal length" might be interpreted as: from that center, you look along the four directions until you encounter a 0 or the edge; those are the arms. Their lengths are determined by the continuous stretch of 1s. That's the natural reading: the arms are the sequences of 1s emanating from the center. If the grid has a longer stretch, the arm is longer. So the arm length is not a choice; it's fixed by the grid. So for (2,1), the left arm length is 1 (since immediate left is 1 but next left is 0? Actually in all-ones grid, left arm from (2,1): positions: (2,0) is 1, (2,-1) out of bounds. So left arm length =1 (excluding center). Right arm: positions: (2,2)=1, (2,3)=1, (2,4)=1, then out => length 3. So lengths are 1 and 3, not equal. So it's not a cross because the arms (as defined by the grid) are not equal. So (2,1) is not a cross. That matches the condition that all four arm lengths must be equal.
Thus in an all-ones 5x5 grid, only the center cell has equal distances to edges (since the grid is symmetric only at the center). So only one cross. That seems intuitive: a perfect plus sign only at the exact center of a symmetric plus shape. If you have a larger plus shape that is not symmetric? Actually for arms to be equal, the distances to the edges in each direction from the center must be the same. That means the center must be centrally located such that the number of rows above equals rows below, and columns left equals columns right. So the center must be at the midpoint of the cross's bounding box. So if you have a cross shape that is of arm length L, then the center must be such that there are at least L cells above, below, left, right. So the cross shape's bounding box is (2L+1)x(2L+1). So the center is at the center of that box. So any cross of arm length L has its center at a cell that has at least L cells in each direction, but also the actual arm lengths are at least L. However, for the arms to be exactly equal, they must be exactly the same length. But if there are more than L cells in some direction, the arm length is actually longer. So for the arms to be equal, we need the number of consecutive 1s in each direction to be exactly the same. That means the cell's distances to the next 0 or boundary must be equal in all four directions. That is a strict condition. So in an all-ones grid, the only cell that has equal distances to the boundaries is the center (if dimensions are odd). If dimensions are even, there may be no cell with exact equality because distances differ by 1? For example, 4x4 all-ones: For cell (1,1): up distance = 1 (cells above: row0), down = 2 (rows 2,3), left=1, right=2. Not equal. (1,2): up=1, down=2, left=2, right=1? Not equal. So no cross. So only when grid has odd dimensions and center cell may have equal distances? Actually it's more about the actual runs, not just boundaries. If the grid is all ones, the runs are bounded by grid edges. So equality requires that i = n-1-i and j = m-1-j => i = (n-1)/2 and j = (m-1)/2, so only if n and m are odd. So at most one cross. That seems too restrictive; maybe the problem expects that the arms can be of equal length but not necessarily maximal; we can consider a cross of a particular length L, and we don't require that beyond L there are zeros; extra ones don't invalidate the cross. That is, a cross of length L exists at center if for each direction there are at least L consecutive 1s. Then the cross of length L is defined as the set of cells at distance ≤ L along the axes. That set is a cross regardless of what's beyond. So in an all-ones grid, for any cell that has at least L cells in each direction, there is a cross of length L. The maximum possible L for that cell is min(distance to edges). So the number of crosses at that cell is min(distance to edges). Because L can range from 1 to that min. So total crosses would be sum over cells of min(distance to edges). That would be many. This interpretation yields many crosses in a large all-ones grid. Which interpretation is more common? I need to decide.
Let's read the problem statement again: "You are given a 2D grid of integers. Write a function to find the number of 'crosses' of 1s. A cross is a 1 with four arms of equal length." It does not say "maximal" or "the arms must be exactly that length and no longer". It says "a cross is a 1 with four arms of equal length." That could be interpreted as: we have a central 1, and from it, in each direction, there is an arm consisting of some number of consecutive 1s (all 1s) and the lengths of these four arms are equal. The arms could be of any length (≥1). There is no requirement that beyond the arm there is a 0. So the arm length is simply the number of consecutive 1s you consider; you can choose a length L as long as the grid has at least L 1s in that direction. So you can have multiple crosses at the same center with different arm lengths. I think this is the intended meaning because they say "a cross is a 1 with four arms of equal length." They don't say "the arms extend until a zero is encountered" or "the arms are maximal". They just say the arms have equal length. That implies that for a given cross, the arms have a specific length L. So we need to count all such (center, L) pairs.
Moreover, if they wanted to count only maximal crosses, they might have said "a cross is a maximal set of 1s forming a plus shape" or something. But they didn't. So I'm leaning toward counting all possible crosses (all L's). But we must check typical usage: In grid pattern counting, the phrase "a cross" often refers to the shape itself, not necessarily maximal. For instance, in a matrix, a "plus sign" can be of any order. The "order" is the arm length. Usually if they just say "plus sign", it could be any order. So if they ask "count the number of plus signs", they might mean count all plus signs of any order.
Let's try to see if there is a known problem: "Count the number of crosses in a binary matrix" - I recall a solution using four direction arrays and then for each cell, the number of crosses with that center is min(up, down, left, right) - 1. Yes! That rings a bell. I think I've seen that. The logic: The maximum arm length (excluding center) that can be formed at cell (i,j) is min(up[i][j], down[i][j], left[i][j], right[i][j]) - 1, because up etc. include center. And that maximum is the number of crosses (since for each length from 1 to that max, there is a cross). So total crosses = sum over cells of that max. That is a classic problem. I'm pretty sure I've seen it. So the answer is sum_{i,j} max(0, min(up[i][j], down[i][j], left[i][j], right[i][j]) - 1). That counts all crosses.
But wait: In that sum, we are counting each possible cross (center, arm length). However, note that for a given cross of arm length L, the center is fixed. So each cross corresponds to one center and one L. So sum_{centers} (max arm length) counts each cross exactly once. That makes sense.
Now, which interpretation matches the given example? The problem statement doesn't provide sample input/output, so we must rely on reasoning. Since they ask to "explain your algorithm", we can present either, but we should clarify which count we are computing. As a responsible developer, we should state assumptions and perhaps consider both? But likely they expect the sum of min-1. Because that's a more interesting problem: we need to compute four DP arrays and then sum. Counting only centers would be simply checking if min>=2. That's too trivial. Counting all crosses requires summing the min-1, which is a bit more nuanced.
Also, if we only count centers with equal arms, we require equality of up, down, left, right inclusive? Actually equality of excl lengths means up_incl-1 = down_incl-1 = left_incl-1 = right_incl-1 => up_incl = down_incl = left_incl = right_incl. That's a stricter condition than just min>=2. That is also trivial to check after computing DP. But summing min-1 is more general and yields higher counts. Which one is more likely? Let's examine the phrase "equal length". If we count all crosses, we are effectively saying for each center, any L such that each direction has at least L cells gives a cross of length L. That doesn't require that the actual maximal arm lengths are equal; it requires that we can find an L that is <= each. But the cross we count for a given L is a cross of exactly length L, and its arms are of length L. So we need to check that for that L, the arms we take are of length L, and they are equal. Since we choose L, the arms we consider are exactly L cells in each direction. Those cells exist as long as the grid has at least L consecutive 1s. So the condition for existence of a cross of length L at (i,j) is: up_incl[i][j] >= L+1, down_incl[i][j] >= L+1, left_incl[i][j] >= L+1, right_incl[i][j] >= L+1. (L+1 because inclusive count includes center). So for a given center, the number of possible L is the maximum L such that all four inclusive counts >= L+1. That max L = min(up_incl, down_incl, left_incl, right_incl) - 1. So the total crosses = sum over cells of that max L (if positive). That is a clean formula.
Now, does that count crosses that have arms that are not necessarily maximal? Yes, it counts all L from 1 to that max. So that seems plausible.
Now, is there any confusion: If a cell has up_incl=5, down_incl=5, left_incl=5, right_incl=5, then max L = 4. That means there are crosses of length 1,2,3,4. That is 4 crosses. That seems plausible: a long plus sign contains plus signs of smaller orders.
If they meant only maximal cross, they would count 1 per cell (if min>1). But they didn't say "maximal".
Thus I think the intended answer is total number of crosses = sum_{i,j} max(0, min(up,down,left,right) - 1). Because it's a known pattern.
But we should confirm with known resources. I recall a problem from GFG: "Count number of crosses in a matrix". I will try to recall the solution. I think they said: "For each cell, find the number of consecutive 1's in all four directions. Then if the minimum of these four values is greater than 1, the cell can be the center of a cross. The number of crosses having that cell as the center is the minimum of the four values minus 1." And sum them. Yes, that seems right.
Let me simulate a small example to see what that yields:
Grid:
1 1 1
1 1 1
1 1 1
All 3x3 ones. For each cell:
- Center (1,1): up=2, down=2, left=2, right=2 => min=2 => crosses from that cell = 2-1 =1. So contributes 1.
- Corner (0,0): up=1, down=3, left=1, right=3 => min=1 => crosses = 0.
- Edge (0,1): up=1, down=3, left=2, right=2 => min=1 => 0.
- Edge (1,0): similar.
- Edge (1,2): up=2, down=2, left=3, right=1? Actually (1,2): up=2, down=2, left=3 (since left_incl: (1,0)=1, (1,1)=2, (1,2)=3), right=1 => min=1 =>0.
- etc. So total =1.
So only one cross total. That matches both interpretations? In this grid, only center qualifies for any cross, and it has max arm length 1, so both count 1.
Now consider a 5x5 all ones grid. Using sum of min-1:
For each cell (i,j):
- up = i+1
- down = n-i
- left = j+1
- right = m-j
min = min(i+1, n-i, j+1, m-j). Then crosses = max(0, min-1). Sum over all cells. That sum would be sum_{i,j} max(0, min(i, n-1-i, j, m-1-j)). Since min-1 = min(i, n-1-i, j, m-1-j). Actually because up = i+1 => up-1 = i; down-1 = n-1-i; left-1=j; right-1 = m-1-j. So min(up,down,left,right)-1 = min(i, n-1-i, j, m-1-j). Because min(i+1, n-i, j+1, m-j) - 1 = min(i, n-1-i, j, m-1-j)? Check: min(i+1, n-i, j+1, m-j) - 1 = min(i+1-1, n-i-1, j+1-1, m-j-1) only if we subtract 1 from the min? Not exactly: min(A,B,C,D) - 1 = min(A-1, B-1, C-1, D-1)? That's not always true. But note: A = i+1, B = n-i, C = j+1, D = m-j. So A-1 = i, B-1 = n-i-1 = n-1-i, C-1 = j, D-1 = m-j-1 = m-1-j. Since min(A,B,C,D) - 1 = min(i, n-1-i, j, m-1-j) if the minimum of A,B,C,D is not affected by subtracting 1? Actually, if we have min(A,B,C,D) = X, then X-1 is not necessarily equal to min(A-1,B-1,C-1,D-1). Example: A=2, B=5, C=3, D=4: min=2, min-1=1; min(A-1=1, B-1=4, C-1=2, D-1=3)=1. That matches. Another: A=3, B=5, C=4, D=6: min=3, min-1=2; A-1=2, others:4,3,5 => min=2. Works because subtracting 1 from all doesn't change the relative ordering? Actually if the minimum A is unique, then min(A-1, others-1) = A-1. If there is a tie, still subtract 1 from each yields same relative order? Because subtracting same constant from all shifts all values equally, so the argmin remains same, and min(new) = min(old)-1. Yes, because min(X_i - 1) = min(X_i) - 1. Since subtracting 1 from each is a monotonic shift, the minimum shifts by 1. So indeed min(A,B,C,D) - 1 = min(A-1, B-1, C-1, D-1). So that's true. So crosses = min(up-1, down-1, left-1, right-1) = min(i, n-1-i, j, m-1-j). So for 5x5: n=5,m=5. For cell (2,2): min(2,2,2,2)=2 => contributes 2. So total crosses = sum_{i,j} min(i,4-i,j,4-j). Let's compute sum manually for 5x5: i=0..4, j=0..4.
We can compute by distance to nearest border: d = min(i,4-i,j,4-j). For each d>0, contributes d. So for d=0: cells with min=0 contribute 0. d=1: cells where min>=1 but not 2. Count? The grid of size 5: the cells with min >=1 are those not on border. Actually border cells have i=0 or i=4 or j=0 or j=4 => min=0. So interior 3x3 grid (i=1..3, j=1..3) have min>=1. For those, min values: for (1,1): min(1,3,1,3)=1; (1,2): min(1,3,2,2)=1; (1,3): min(1,3,3,1)=1; (2,1): min(2,2,1,3)=1; (2,2): min(2,2,2,2)=2; (2,3): min(2,2,3,1)=1; (3,1): min(3,1,1,3)=1; (3,2): min(3,1,2,2)=1; (3,3): min(3,1,3,1)=1. So sum of min = 1 for 8 cells + 2 for 1 cell = 10. So total crosses = 10. That is sum of max arm lengths across all centers. So if we count all crosses (each length separately), total =10. If we count centers that have at least one cross, we have how many? All interior 3x3 have at least one cross? Actually check: For (1,1): up_excl = up_incl-1? up_incl = i+1=2 => up_excl=1; down_incl= n-i=5-1=4 => down_excl=3; left_excl=j=1; right_excl=m-1-j=3. The four excl lengths are (1,3,1,3) not equal. But for a cross to exist, do we need them equal? In the summing method, we are counting crosses of length L that are possible. But for (1,1), we have up_excl >=1, down_excl >=1, left_excl >=1, right_excl >=1, so there is a cross of length 1? For a cross of length 1, we need that each direction has at least 1 cell. That is true. But do we also require that the arm lengths we use are exactly equal? Yes, we set L=1. That uses exactly one cell in each direction. Those cells are present. So (1,1) should have at least a cross of length 1. But in our calculation for (1,1), min(up_incl, down_incl, left_incl, right_incl) = min(2,4,2,4)=2 => Lmax = 1. So it contributes 1 cross. That's consistent: (1,1) contributes 1 cross (L=1). But earlier I thought (1,1) does not have equal arms? But arms lengths for a cross of length 1 are exactly 1. They are equal. The fact that there are extra 1s beyond doesn't matter; we are only using the first one. So (1,1) does have a cross of length 1. So under the sum interpretation, (1,1) is counted. Under the "only maximal cross" or "arms lengths equal in the full run" interpretation, (1,1) would not be counted because its full arm lengths are (1,3,1,3) not equal. So that's a key difference. Which one is more natural? Let's think: In a 5x5 all-ones grid, look at cell (1,1). It is not the center of a symmetric plus sign if you consider the entire plus sign of maximal size, because to the left there is only 1 cell (j=0) before edge, to the right there are 3 cells. So the arms are not symmetric. However, you can still see a small plus sign centered at (1,1) using just the immediate neighbor cells: up (0,1), down (2,1), left (1,0), right (1,2). Those are all 1s. That is a cross of size 1. So does that count as a cross? If you look at the grid, there is a plus sign at (1,1) of size 1. It's a distinct shape. So why wouldn't we count it? The definition says "a cross is a 1 with four arms of equal length." For the cross of size 1, the arms have length 1. That's true. So (1,1) qualifies as a cross of size 1. So we should count it. Therefore the interpretation that counts only cells where the full runs are equal would miss many crosses. That seems unlikely if they want the total number of crosses. Because in an all-ones grid, there are many crosses, not just the one at the center. For example, in a 5x5 all-ones, how many crosses of size 1 are there? Any cell that has at least one neighbor in each direction (i.e., not on border) qualifies. That's the interior 3x3 = 9 cells. Plus possibly crosses of size 2? Only the center (2,2) qualifies because it needs at least 2 in each direction. So there is 1 cross of size 2. So total crosses = 9 (size1) + 1 (size2) = 10. That matches our sum calculation (10). So it's a nice answer: interior cells contribute at least 1, center contributes 2. That seems like a non-trivial count. So the sum approach yields a more interesting problem. The simpler approach (count centers where full runs are equal) would only count cells where the distances to edges are equal in both directions. That would be only the center (if odd dimensions). In 5x5, that gives 1. That's less interesting. In many grids, that count might be small. The sum approach yields interesting distribution.
Thus, I strongly believe the intended solution is to compute for each cell the number of consecutive 1s in all four directions (including the cell itself), then the number of crosses centered at that cell is max(0, min(up, down, left, right) - 1). Sum over all cells to get total crosses.
This is a classic DP + counting problem.
We should also consider if arm length can be zero? No, we subtract 1 so we get non-negative. If min value is 1 (i.e., the cell is 1 but at least one direction has only the center), then min-1=0 => no cross. So condition is effectively each direction must have at least 2 including center => immediate neighbor exists.
Thus algorithm:
- Initialize n = number of rows, m = number of columns.
- Create four 2D arrays: up, down, left, right, all of size n x m, initialized to 0.
- Fill up and left in one pass (top-left to bottom-right):
for i from 0 to n-1:
for j from 0 to m-1:
if grid[i][j] == 1:
up[i][j] = 1 + (up[i-1][j] if i>0 else 0)
left[i][j] = 1 + (left[i][j-1] if j>0 else 0)
else:
up[i][j] = left[i][j] = 0
- Fill down and right in another pass (bottom-right to top-left):
for i from n-1 down to 0:
for j from m-1 down to 0:
if grid[i][j] == 1:
down[i][j] = 1 + (down[i+1][j] if i < n-1 else 0)
right[i][j] = 1 + (right[i][j+1] if j < m-1 else 0)
else:
down[i][j] = right[i][j] = 0
- Initialize count = 0.
For each cell (i,j):
if grid[i][j] == 1:
min_len = min(up[i][j], down[i][j], left[i][j], right[i][j])
// arm length = min_len - 1
if min_len > 1: // to avoid negative
count += min_len - 1
- Return count.
Edge: grid may contain integers other than 0/1? It says grid of integers. We treat 1 as valid, any non-1? Probably we consider only 1 as part of cross, others are obstacles. So condition grid[i][j]==1.
Complexities: O(nm) time, O(nm) space. We can reduce space by using only two arrays if we process row by row? But we need all four values for each cell simultaneously, so we need to store at least two of them, but we can compute up and left in one pass and store them; then compute down and right in second pass and combine. That uses O(n*m) anyway. That's fine.
We should also consider whether overlapping crosses share arms? That's fine.
Now, we must produce a function. The function signature: probably something like int countCrosses(vector<vector>& grid) or similar. We'll write in Python for clarity, but we can also give generic.
We need to explain algorithm. We'll explain DP and counting.
Potential pitfalls: Large numbers, but Python int fine. We'll ensure to handle empty grid.
We'll also mention that we treat the grid as binary (1s and 0s) but any integer not equal to 1 is considered 0.
Now, I'll produce final answer: function and explanation.
But before finalizing, let's double-check the definition: "A cross is a 1 with four arms of equal length." This could also be interpreted as: for each cross, the lengths of the four arms are exactly equal, but they could be any length. So our counting method counts each possible arm length L that works. That's sum of min-1.
But is there any scenario where a cell has up_incl=2, down_incl=2, left_incl=3, right_incl=3. Then min=2 => max L=1. So it contributes 1 cross (L=1). That's correct because there is a cross of length 1: arms use one cell each direction; left and right have more but that's okay. So (1,1) in 5x5 all-ones has up_incl=2, down_incl=4, left_incl=2, right_incl=4. min=2 => contributes 1. So indeed interior cells contribute 1. That matches our earlier manual count: 9 interior cells each contributed 1, center contributed 2. So total 10. Good.
Now, what about a cell that is on the edge? min would be 1 (or maybe less if grid[i][j]==0). So contributes 0.
Thus algorithm yields total crosses.
Now, we should also consider if the grid might have negative numbers or other values; we only treat 1 as valid.
Now, let's craft a thorough explanation.
We'll say:
- We define for each cell the number of consecutive 1s in the four directions including the cell.
- Then for a cell to be the center of a cross with arm length L (L>=1), we need that there are at least L+1 consecutive 1s in each direction (including the center), i.e., up[i][j] >= L+1, etc.
- The maximum possible L is min(up[i][j], down[i][j], left[i][j], right[i][j]) - 1.
- If this maximum is positive, the cell contributes that many crosses (for L=1 to max).
- Sum over all cells.
We'll also show an example.
Now, implement in Python.
Potential edge: large grids? Use fast loops.
We'll provide code:
def count_crosses(grid):
if not grid or not grid[0]:
return 0
n, m = len(grid), len(grid[0])
up = [[0]*m for _ in range(n)]
left = [[0]*m for _ in range(n)]
# up and left
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
up[i][j] = 1 + (up[i-1][j] if i > 0 else 0)
left[i][j] = 1 + (left[i][j-1] if j > 0 else 0)
else:
up[i][j] = left[i][j] = 0
down = [[0]*m for _ in range(n)]
right = [[0]*m for _ in range(n)]
for i in range(n-1, -1, -1):
for j in range(m-1, -1, -1):
if grid[i][j] == 1:
down[i][j] = 1 + (down[i+1][j] if i < n-1 else 0)
right[i][j] = 1 + (right[i][j+1] if j < m-1 else 0)
else:
down[i][j] = right[i][j] = 0
total = 0
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
min_arm = min(up[i][j], down[i][j], left[i][j], right[i][j])
total += max(0, min_arm - 1)
return total
We can also reduce space by using one array for up and down? Actually we could compute up and left, then reuse them for down and right if we store them separately, but it's fine.
Now, we need to produce final answer with explanation.
I'll write a clear step-by-step explanation.
Potential improvements: We can compute total on the fly in the second pass to avoid storing both down and right arrays simultaneously? Actually we need up and left from first pass, and we compute down and right in second pass; we could compute min and add to total immediately after computing down and right for that cell, because up and left are already computed. That would reduce memory to only up, left, down, right but we can even avoid storing down and right arrays entirely if we compute them and then combine with up and left on the fly. However, we need both up and left for each cell while computing down and right. We could do: in the second pass, for each cell we compute down_val = 1 + (down[i+1][j] if i < n-1 else 0) and right_val similarly, then we have up[i][j] and left[i][j] from previous arrays. Then we can compute min_val = min(up[i][j], down_val, left[i][j], right_val) and add contribution. Then we store down_val and right_val in temporary variables, but we also need to pass them to the next cell (for the DP we need to store down[i][j] for use by the cell above? Actually in the bottom-up pass, we need down[i][j] to compute down for cell above (i-1,j). So we need to store down[i][j] for later use by the next iteration (i-1). So we need an array for down, or we can do two passes: one for down, one for right, then combine. Or we can store down and right arrays. It's fine.
But we can also compute all four in two passes and store all four; memory is O(n*m). Acceptable.
Now, produce final answer.
But also consider the possibility that grid values may be something else; we treat 1 as valid.
Now, produce final solution with explanation.
We'll also include a small example to illustrate.
I'll now craft the final answer.
Solution Explanation
We are given a 2‑dimensional grid grid containing integers.
A cross is defined by a central cell (i, j) that contains a 1 and has four arms of equal length extending in the four orthogonal directions (up, down, left, right).
For a cross with arm length L ( L ≥ 1 ) we need:
- the
L cells directly above (i, j) are all 1,
- the
L cells directly below (i, j) are all 1,
- the
L cells directly left of (i, j) are all 1,
- the
L cells directly right of (i, j) are all 1.
If a cell has at least L consecutive 1s in every direction, then a cross of length L exists with that cell as the centre.
The largest possible arm length for a centre (i, j) is
Lmax(i, j) = min( up[i][j], down[i][j], left[i][j], right[i][j] ) – 1
where
up[i][j] = number of consecutive 1s ending at (i, j) when we go downwards (i.e. includes the cell itself and all cells above it),
down[i][j] = number of consecutive 1s starting at (i, j) and going downwards,
left[i][j] = number of consecutive 1s ending at (i, j) when we go rightwards,
right[i][j] = number of consecutive 1s starting at (i, j) and going rightwards.
If Lmax(i, j) > 0, then the centre contributes exactly Lmax(i, j) different crosses (one for each possible arm length 1 … Lmax).
Summing Lmax(i, j) over all cells gives the total number of crosses in the grid.
The problem therefore reduces to computing the four directional “consecutive‑1” arrays and then summing max(0, min(up,down,left,right) - 1) for every cell that contains a 1.
Algorithm
- Initial checks – if the grid is empty, return
0.
- First pass (top‑left → bottom‑right)
Compute up and left:
up[i][j] = 0 if grid[i][j] != 1
else 1 + (up[i-1][j] if i>0 else 0)
left[i][j] = 0 if grid[i][j] != 1
else 1 + (left[i][j-1] if j>0 else 0)
- Second pass (bottom‑right → top‑left)
Compute down and right and at the same time add the contribution to the answer:
down[i][j] = 0 if grid[i][j] != 1
else 1 + (down[i+1][j] if i < n-1 else 0)
right[i][j] = 0 if grid[i][j] != 1
else 1 + (right[i][j+1] if j < m-1 else 0)
After computing these four values for (i, j):
if grid[i][j] == 1:
min_len = min(up[i][j], down[i][j], left[i][j], right[i][j])
ans += max(0, min_len - 1)
- Return
ans.
Correctness Proof
We prove that the algorithm returns exactly the number of crosses.
Lemma 1
For any cell (i, j), after the first pass up[i][j] equals the number of consecutive 1s in column j ending at row i (including (i, j)).
Similarly left[i][j] equals the number of consecutive 1s in row i ending at column j (including (i, j)).
Proof. By induction over the order of traversal (top‑left to bottom‑right).
Base: first row or first column – the recurrence reduces to 1 if the cell itself is 1, otherwise 0, which is exactly the count.
Induction step: if grid[i][j] == 1 then the streak is the previous streak in the same direction plus the current cell; otherwise it is 0. ∎
Lemma 2
After the second pass, for any cell (i, j), down[i][j] equals the number of consecutive 1s in column j starting at row i (including (i, j)), and right[i][j] equals the number of consecutive 1s in row i starting at column j (including (i, j)).
Proof. Symmetric to Lemma 1, using the reverse traversal order. ∎
Lemma 3
For a cell (i, j) with grid[i][j] == 1, let
M = min( up[i][j], down[i][j], left[i][j], right[i][j] )
Then the maximum possible arm length of a cross centred at (i, j) is Lmax = M – 1.
Moreover, for every integer L with 1 ≤ L ≤ Lmax there exists a cross of arm length L centred at (i, j).
Proof.
up[i][j] includes the centre, so the number of cells strictly above the centre is up[i][j] – 1.
Similarly, the numbers of cells above, below, left, and right (excluding the centre) are
up[i][j]‑1, down[i][j]‑1, left[i][j]‑1, right[i][j]‑1.
For a cross with arm length L we need each of these four quantities to be at least L.
That is equivalent to
up[i][j] ≥ L+1
down[i][j] ≥ L+1
left[i][j] ≥ L+1
right[i][j]≥ L+1
The largest L satisfying all four inequalities is
Lmax = min(up, down, left, right) – 1 = M – 1.
If Lmax ≥ 1, then for each L from 1 to Lmax the inequalities hold, hence each such L defines a valid cross. ∎
Lemma 4
The algorithm adds exactly Lmax to the answer for every cell (i, j) that is the centre of at least one cross, and adds 0 otherwise.
Proof.
During the second pass we compute min_len = M.
If grid[i][j] == 1, the algorithm adds max(0, M-1).
If M-1 ≥ 0 then M-1 = Lmax (by Lemma 3).
If M-1 < 0 (i.e. M = 0 or M = 1) there is no cross (Lmax ≤ 0), and the algorithm adds 0. ∎
Theorem
The value returned by the algorithm equals the total number of crosses in the grid.
Proof.
Each cross is uniquely identified by its centre (i, j) and its arm length L.
By Lemma 3, for a fixed centre the possible arm lengths are exactly 1 … Lmax.
By Lemma 4 the algorithm adds Lmax for that centre.
Summing over all centres therefore counts every possible (centre, L) pair exactly once, i.e. every cross. ∎
Complexity Analysis
Time:
- First pass:
O(n·m)
- Second pass:
O(n·m)
Total O(n·m).
Space:
Four auxiliary n × m integer arrays → O(n·m) additional space.
(We could reduce to O(n·m) is already optimal; further reduction is possible but not needed.)
Reference Implementation (Python)
def count_crosses(grid):
"""
Returns the total number of crosses of 1's in the grid.
A cross is a centre cell containing 1 with four arms of equal length L>=1.
For each centre, the maximum possible arm length is min(up,down,left,right)-1,
and that many crosses (for lengths 1..max) exist.
"""
if not grid or not grid[0]:
return 0
n, m = len(grid), len(grid[0])
# DP arrays
up = [[0] * m for _ in range(n)]
left = [[0] * m for _ in range(n)]
# first pass: fill up and left
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
up[i][j] = 1 + (up[i-1][j] if i > 0 else 0)
left[i][j] = 1 + (left[i][j-1] if j > 0 else 0)
else:
up[i][j] = left[i][j] = 0
down = [[0] * m for _ in range(n)]
right = [[0] * m for _ in range(n)]
total = 0
# second pass: fill down and right, and accumulate answer
for i in range(n-1, -1, -1):
for j in range(m-1, -1, -1):
if grid[i][j] == 1:
down[i][j] = 1 + (down[i+1][j] if i < n-1 else 0)
right[i][j] = 1 + (right[i][j+1] if j < m-1 else 0)
min_len = min(up[i][j], down[i][j], left[i][j], right[i][j])
if min_len > 1: # min_len-1 >= 1
total += min_len - 1
else:
down[i][j] = right[i][j] = 0
return total
The function follows exactly the algorithm proven correct above and runs in linear time with respect to the grid size.