You are given a 2D grid of integers. Write a function to find the number of "X-shapes" of 1s. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given a 2D grid of integers. We need to find the number of "X-shapes" of 1's. What is an "X-shape"? Probably a pattern that looks like an X: i.e., a cross where there are 1's at positions (i,j), (i+1,j+1), (i+2,j+2), etc? Actually, typical definition: An X-shape might be defined as a set of cells that form a diagonal cross: both main diagonal and anti-diagonal crossing at a center. But the problem statement is vague. Possibly it means a pattern like:
1
1
1
1
1
or maybe a 3x3 X? Let's think: Many problems ask for "plus shapes" or "X shapes" of 1s. For example, "count the number of X shapes of 1s" could mean find connected components that are shaped like an X? Or maybe they mean a specific shape: a central cell with arms extending diagonally in all four directions? That's like an X. But then it's a cross with diagonals.
Alternatively, might be a pattern like:
1 0 1
0 1 0
1 0 1
That's an X shape of size 3? But then all cells are 1. But the shape is like an X: two diagonals.
But the phrase "X-shapes" of 1's could be interpreted as connected components of 1's that have the shape of an X. But it's ambiguous.
We need to infer from typical coding problems. Perhaps it's from a known problem: "Count the number of X shapes in a binary matrix". I recall a problem: Given a grid of 0s and 1s, count the number of X shapes made of 1s. An X shape is defined as:
There is a center cell.
From the center, there are exactly k cells in each of the four diagonal directions (up-left, up-right, down-left, down-right) that are 1, and these arms are contiguous? Or maybe just the pattern of an X: the cell itself and its four diagonal neighbors? That would be a small X of size 1? Actually, an X of size 1 might be just a single cell? But that would be trivial.
Maybe the X shape is defined as: a set of 1s that form a continuous diagonal line in both directions, crossing at a point. Like:
For a given center (i,j), if there are 1s at (i,j), (i-1,j-1), (i+1,j+1) and (i-1,j+1), (i+1,j-1) then that's an X of size 1? That would be a plus but rotated 45 degrees? Actually, that's exactly an X: a cross with diagonals.
But then the shape might be larger: For size 2, we would have:
1
1 1
1
1 1
1
? That's more like a star.
Maybe it's like this: An X shape of order k consists of a central cell and k cells in each of the four diagonal directions, all 1s. So total cells = 1 + 4*k. For k=1, total 5 cells: center plus one in each diagonal direction. That's a typical X shape.
But if we have such a pattern, we need to count how many such X shapes exist. They may overlap? Possibly we need to count distinct shapes, maybe centered at each cell, we check if there is an X shape of at least size 1? Or maybe we need to count all possible X shapes of any size? The problem says "number of 'X-shapes' of 1's". It might be counting connected components that are exactly an X shape? But that seems complicated.
Let's search memory: I think I've seen a problem: "Given a 2D grid of 0s and 1s, find the number of X shapes". The definition: An X shape is formed by 1s that are connected diagonally. Actually, maybe it's about connected components when considering 8-directional connectivity? But then an X shape might be a component that looks like an X? That is subjective.
Maybe it's simpler: The grid contains only 0s and 1s. We need to count the number of occurrences of the pattern:
1
1
1
1
1
That is like a diagonal line of length 5 with a bend? That's not an X.
Wait, maybe it's the pattern:
1 0 1
0 1 0
1 0 1
That's an X shape. And we need to count how many such 3x3 subgrids have exactly that pattern? That would be "count X shapes". But then the shape is fixed size. But the problem statement says "X-shapes" without specifying size, maybe we need to count all X shapes of any size, like larger Xs.
Let's think about typical interview questions. One common problem: "Count the number of islands" (connected components of 1s). Another: "Count the number of plus signs" or "count the number of crosses". I recall a problem: "Given a binary matrix, count the number of X shapes (crosses) formed by 1s." Possibly they define an X shape as: a central 1 with 1s in all four diagonal directions, and optionally more in those directions? Actually, a cross (plus) is defined as central cell with arms extending horizontally and vertically. An X would be central cell with arms extending diagonally. But they might allow arms of any length, as long as they are contiguous? So an X shape of order k means that there is a cell (i,j) such that for all d=1..k, cells (i+d, j+d), (i-d, j-d), (i+d, j-d), (i-d, j+d) are all 1. And these cells must be present (within bounds). That seems plausible.
Thus we count each such center that satisfies for some k>=1? Or we need to count the number of X shapes, where each shape is defined by its center and size? Possibly we count each possible X shape as a distinct shape, meaning if a center can support an X of size 2, then that includes the X of size 1 as well? But maybe we want the maximal one? Or maybe we want to count the number of X shapes (any size) that are present, even if they overlap. That is similar to counting all "plus signs" in a grid where plus signs are counted for each center with given arm length. There is a known problem: "Count number of plus signs in a binary matrix" where a plus sign is defined by a central 1 and arms of 1s extending in four directions. The solution precomputes continuous 1s in each direction for each cell and then counts how many plus signs exist (each possible arm length). That yields O(n^3) maybe but with precomputation O(n^2). For X shapes, it's similar but using diagonal directions.
Thus, likely the problem: Count the number of X shapes. Each X shape is defined by a center cell (i,j) and an arm length L (>=1) such that for all t from 1 to L, the cells at (i+t, j+t), (i-t, j-t), (i+t, j-t), (i-t, j+t) are 1. The center itself must be 1. Possibly we require that the arms are not broken (i.e., continuous). So the number of X shapes is the sum over all cells of the maximum L such that the condition holds? Actually, if we count each possible L separately, then if an X of size 2 exists, it also contains X of size 1. But are those considered separate shapes? Typically, when counting "plus signs", they count distinct plus signs (each with a specific center and arm length). So yes, if a cell can form a plus of arm length 2, that means it also can form a plus of arm length 1, and we count both. But sometimes they count only the maximal plus (the largest possible). Which one? Need to infer.
Let's search memory: There is a LeetCode problem: "Count Number of Largest Plus Sign" but that's different. Another: "Number of X-shaped patterns". Not sure.
Maybe the problem is from a contest: "X-shapes" where you need to find the number of connected components that are shaped like an X. But then we need to define what an X-shaped component is. Possibly it's a component that is exactly the set of cells that form a perfect X (i.e., two diagonal lines crossing). That would require the component to have exactly 2k+1 cells? Actually, two diagonals crossing: For size k (arm length), total cells = 2k+1? Let's see: For an X of arm length k (distance from center to tip), the two diagonals each have 2k+1 cells? Actually, the main diagonal from top-left to bottom-right going through center includes cells (i-k,j-k) to (i+k,j+k), that's 2k+1 cells. The anti-diagonal also includes 2k+1 cells, but they share the center, so total unique cells = (2k+1)+(2k+1)-1 = 4k+1. That matches earlier: 1 + 4*k. So an X shape of order k has 4k+1 cells. That is the typical cross with diagonals.
Thus, an X shape is exactly those cells. So we need to count how many such shapes exist in the grid, where all cells in that shape are 1, and they are exactly that pattern? But if we have a larger X that includes a smaller X, then both patterns exist as subshapes. For example, if we have an X of size 2 (k=2), then at the center we have also an X of size 1 (k=1) because the inner 5 cells also form an X. So they would be separate shapes overlapping. Usually, we count all X shapes regardless of overlap. That would be like counting all submatrices that match the pattern.
But counting all submatrices of shape X for all possible centers and all possible arm lengths would be O(n^3) if we naively check each center and each k. But we can precompute continuous 1s in each diagonal direction. For each cell, we can compute the maximum arm length L such that all four diagonal directions have at least L consecutive 1s (including the center? Actually, we need that for each direction, the count of consecutive 1s from the cell outward along that diagonal is at least L. But careful: For an X shape of size k, we need that for each direction, the arm length k is present. So the maximum possible k for a center is min( UL, UR, DL, DR ), where UL is the number of consecutive 1s up-left from (i,j) including? Typically, we precompute for each cell the length of contiguous 1s ending at that cell in each direction. But for a center, we need the number of consecutive 1s extending outward in each diagonal direction. So we can precompute arrays: up-left, up-right, down-left, down-right. Then for each cell, the maximum arm length = min(up-left[i][j], up-right[i][j], down-left[i][j], down-right[i][j]) - 1? Actually, careful: If we define up-left[i][j] as the number of consecutive 1s along the up-left diagonal ending at (i,j) (including (i,j)), then the number of cells from the center outward in the up-left direction is that count minus 1? Because at the center, up-left includes the center itself. For arm length 1, we need that the cell itself is 1 (so up-left>=1) and the cell one step up-left is also 1? Actually, for arm length 1, we require cells: center (i,j), (i-1,j-1), (i+1,j+1), (i-1,j+1), (i+1,j-1). That is 5 cells. For up-left direction, the arm is (i,j) and (i-1,j-1). So we need at least 2 consecutive 1s ending at (i,j) along up-left? Because if we have up-left[i][j] >= 2, that means (i,j) and (i-1,j-1) are 1. Similarly, down-left direction: we need down-left[i][j] >= 2 (including (i,j) and (i+1,j-1) maybe? Actually, down-left: direction is down-left, so from (i,j) going down-left, we need (i+1,j-1). That would be part of down-left if we compute down-left as consecutive 1s along that diagonal starting from top? Let's define clearly:
We want for a given center (i,j) and arm length k, we require:
For t = 1..k: (i-t, j-t) is 1 -> that is the up-left direction.
For t = 1..k: (i-t, j+t) is 1 -> up-right.
For t = 1..k: (i+t, j-t) is 1 -> down-left.
For t = 1..k: (i+t, j+t) is 1 -> down-right.
Also center (i,j) must be 1.
So we need to know for each cell the maximum contiguous 1s in each of these directions outward. It might be easier to precompute arrays that give the length of consecutive 1s in each direction starting from the cell and moving outward. But we can also compute "prefix" lengths: For up-left, we can compute UL[i][j] = if grid[i][j]==1 then UL[i-1][j-1]+1 else 0. That gives the number of consecutive 1s ending at (i,j) from the up-left direction. That includes the cell itself. So for center (i,j), UL[i][j] tells how many consecutive 1s are in the up-left diagonal ending at (i,j). That means the cells (i,j), (i-1,j-1), (i-2,j-2), ... up to UL[i][j] cells. So the number of cells from (i,j) going up-left (including (i,j)) is UL[i][j]. To have arm length k in the up-left direction, we need UL[i][j] >= k+1? Because we need cells at distance 1..k, plus the center? Actually, the arm includes cells at distances 1..k, not including center? Wait, we need the cells (i-1,j-1), (i-2,j-2), ... up to (i-k,j-k). That's k cells. And also the center itself. So the total consecutive segment from (i-k,j-k) to (i,j) has length k+1. So UL[i][j] must be at least k+1. Similarly, for up-right direction: UR[i][j] = if grid[i][j]==1 then UR[i-1][j+1]+1 else 0. That gives length of consecutive 1s ending at (i,j) from up-right. To have arm length k in up-right, we need UR[i][j] >= k+1. For down-left: we can compute DL[i][j] = if grid[i][j]==1 then DL[i+1][j-1]+1 else 0? That would be starting from bottom? Actually, to get the length of consecutive 1s going down-left from a cell, we can compute from bottom to top: for i from bottom up, j from left to right? Better: we compute down-left as: if grid[i][j]==1 then DL[i][j] = DL[i+1][j-1] + 1 if we process from bottom to top? But easier: we can compute the lengths in the direction that goes outward from the center. We could compute four arrays: UL (up-left), UR (up-right), DL (down-left), DR (down-right). We need the number of consecutive 1s in each direction starting from the cell and moving outward. The typical method: compute UL and UR by iterating from top-left to bottom-right. For DL and DR, we iterate from bottom-right to top-left. Or we can compute "forward" and "backward" directions.
Standard approach for cross/plus: precompute left, right, up, down. For X, it's diagonals.
So:
UL[i][j] = (grid[i][j]==1) ? UL[i-1][j-1] + 1 : 0, for i>0, j>0, else 1 if grid[i][j]==1.
UR[i][j] = (grid[i][j]==1) ? UR[i-1][j+1] + 1 : 0, for i>0, j<cols-1.
DL[i][j] = (grid[i][j]==1) ? DL[i+1][j-1] + 1 : 0, for i<rows-1, j>0? Actually, to compute down-left, we need to go bottom-up: iterate i from rows-1 down to 0, j from cols-1 down to 0? Let's think: For down-left, we want the number of consecutive 1s along the diagonal going down-left from (i,j). That is cells (i,j), (i+1,j-1), (i+2,j-2), ... So if we compute DL[i][j] = 1 + DL[i+1][j-1] if within bounds and grid[i][j]==1. So we need to iterate i from bottom to top, j from left to right? Actually, j goes from 0 to cols-1, but we need j-1, so we need to ensure j>0. And i+1 must be within rows. So we can iterate i from rows-1 down to 0, and j from 0 to cols-1 (but need j-1, so we need j>0). But careful: when i is large, i+1 might be out of bounds. We can iterate i decreasing from rows-1 to 0, and for each i, iterate j from 0 to cols-1. For j=0, we cannot have j-1, so DL[i][0] = 1 if grid[i][0]==1. But also note that down-left direction from (i,0) would only be itself because next step j-1 negative. So that's fine.
Similarly, DR[i][j] = (grid[i][j]==1) ? DR[i+1][j+1] + 1 : 0. Iterate i from rows-1 down to 0, j from cols-1 down to 0? Because we need j+1 and i+1, so we need to have computed i+1 and j+1 first. So we should iterate i from bottom to top, and j from right to left.
Thus we can compute all four matrices.
Then for each cell (i,j) that is 1, the maximum arm length L_max = min( UL[i][j]-1, UR[i][j]-1, DL[i][j]-1, DR[i][j]-1 ). Because UL[i][j] counts the number of consecutive 1s ending at (i,j) from up-left, which includes the center and the cells before it. The number of cells in that direction from the center outward is UL[i][j]-1 (since the center itself is counted as distance 0). For arm length k, we need at least k cells outward, so UL[i][j] >= k+1 => k <= UL[i][j]-1. So L_max = min(UL[i][j]-1, UR[i][j]-1, DL[i][j]-1, DR[i][j]-1). This L_max is the maximum arm length possible for an X centered at (i,j). Then the number of X shapes centered at (i,j) is L_max (if we count each possible arm length from 1 to L_max). Or if we count only maximal X shapes per center, it would be 1 if L_max>=1. But we need to count total X shapes. The problem statement: "find the number of 'X-shapes' of 1s." Could be interpreted as the total number of X shapes present, counting each distinct shape. Usually, problems like "count the number of plus signs" count each plus sign as a distinct entity, and if a cell can serve as center for plus of arm length up to L, then we count L plus signs (one for each arm length from 1 to L). But I'm not entirely sure.
Let's see if there's any typical interpretation: The phrase "number of X-shapes" might refer to connected components that are shaped like an X. But that would be a different problem: We would need to detect components that exactly match the X pattern (i.e., 4 arms plus center). That would be like counting occurrences of the pattern. But then a large X would also contain smaller Xs as subcomponents? But the component itself would be the whole set of 1s that are connected. If we have a large X shape (say of arm length 2) that is not part of any other 1s, it would be a component of 9 cells. That component is an X shape. If we have an X of arm length 2 and also some extra 1s attached, it might not be a pure X. So that interpretation would require that the component exactly equals the set of cells of an X shape (i.e., it's exactly the two diagonals crossing). That seems more specific and less likely because they'd have to define what an X shape is: the set of cells that form a symmetric cross with diagonals. Possibly they define an X shape as any set of 1s that are connected (8-directionally?) and form an X? That seems messy.
Given it's a coding problem, the likely interpretation is counting all submatrices that match the X pattern of any size. Or counting each center with its maximal arm length as one shape? Actually, let's check similar problems: On LeetCode, there's "Count Submatrices With All Ones", but not X.
Maybe it's from GeeksforGeeks: "Count the number of X shapes in a given matrix". I recall a problem: Given a matrix of characters (like 'X' and 'O'), count the number of X shapes? That's different.
Given we are given integers, maybe it's a binary matrix (0 and 1). We need to count X shapes. Possibly the shape is defined as:
For a cell (i,j) to be the center of an X, we need:
That is a minimal X (size 1). Then we count how many such centers exist. But that's just counting a pattern of size 3x3. That would be too trivial? Possibly they want to count all X shapes of any size, as described earlier.
Let's read the prompt: "You are given a 2D grid of integers. Write a function to find the number of 'X-shapes' of 1s." It doesn't specify the size of the shape. It might be that they assume the X shape is like a plus but rotated 45 degrees, with arms of length at least 1. So we need to count all possible X shapes. The function should return an integer.
We need to write an algorithm and explain it. So we need to choose an interpretation and produce a solution.
Let's think of efficiency: The grid size? Not specified, but typical constraints: rows, cols up to 1000 maybe. So we need an O(nm) or O(nmlog?) solution. If we count all X shapes (each possible center and each possible arm length), we could compute L_max for each cell as described, and then sum L_max over all cells. That would count each X shape exactly once (by its center and arm length). That gives total count = sum_{i,j} L_max(i,j). This is efficient: O(rowscols) time after precomputation of the four diagonal length arrays. That's neat.
If we instead count only maximal X shapes per center, we would count number of cells with L_max>=1. That's also O(n*m). But which one is more plausible? The phrasing "number of X-shapes" could be interpreted as the total number of X shapes present in the grid. Overlapping shapes are counted separately. That is common in pattern counting problems. For example, "count the number of plus signs" on LeetCode? Actually, there is a problem: "Number of Plus Sign" but that counts largest plus sign? Hmm.
Let's search memory: I think there is a known problem: "Given a binary matrix, count the number of X's formed by 1's". I recall a solution that uses DP to preprocess diagonal lengths and then sums min(UL, UR, DL, DR) - 1. Yes! I've seen something like that. The DP gives the maximum cross arm length (for plus) but for X it's diagonals. And then sum of those values gives the count of all X shapes. Because for each cell, the number of X shapes centered at that cell is the maximum arm length. That is a known technique.
Thus, I'll go with: For each cell that is 1, compute L = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1. If L>0, then there are L X shapes centered at (i,j) with arm lengths 1..L. Sum L over all cells gives total X shapes.
But careful: For an X shape of arm length k, the center is counted. But also note that the arms consist of 1s that might be part of other X shapes centered elsewhere. That's fine; we count each shape independently.
Edge cases: If L_max=0, then no X shape of arm length >=1. So if a cell has all four diagonal neighbors 1, then UL[i][j] at least 2? Actually, for arm length 1, we need UL[i][j]>=2, UR>=2,DL>=2,DR>=2. So L_max = min(...)-1 >=1 => min(...)>=2. So if min is 2, then L_max=1, count 1.
But what if the center is at border? UL[i][j] etc will be small. So only interior cells can have X shapes.
We need to ensure that the arms are contiguous and not broken. The DP ensures continuity because UL[i][j] counts consecutive 1s ending at (i,j). So if there is a zero somewhere along the diagonal, the length will be limited.
Thus algorithm steps:
Get grid dimensions: rows = m, cols = n.
Initialize four 2D arrays UL, UR, DL, DR of same size as grid, with zeros.
Compute UL: for i from 0 to m-1, for j from 0 to n-1:
if grid[i][j]==1: UL[i][j] = 1 + (UL[i-1][j-1] if i>0 and j>0 else 0)
else UL[i][j]=0.
Compute UR: for i from 0 to m-1, for j from n-1 down to 0:
if grid[i][j]==1: UR[i][j] = 1 + (UR[i-1][j+1] if i>0 and j<n-1 else 0)
else 0.
Compute DL: for i from m-1 down to 0, for j from 0 to n-1:
if grid[i][j]==1: DL[i][j] = 1 + (DL[i+1][j-1] if i0 else 0)
else 0.
Compute DR: for i from m-1 down to 0, for j from n-1 down to 0:
if grid[i][j]==1: DR[i][j] = 1 + (DR[i+1][j+1] if i<m-1 and j<n-1 else 0)
else 0.
Initialize total = 0.
For each cell (i,j):
if grid[i][j]==1:
L = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1
if L>0: total += L (since arm lengths from 1 to L)
else: skip.
Return total.
But wait: If L_max=0, L becomes -1? Actually, min(...)-1 could be negative if any of the four is 0. But we skip if grid[i][j]==0. But if grid[i][j]==1, then UL[i][j] at least 1, same for others. So min>=1, so min-1 >=0. If any direction has length exactly 1 (only center), then min-1 = 0. So L=0, we add 0. So we can just sum L.
So total = sum(min(UL,UR,DL,DR) - 1) over all cells where grid[i][j]==1? Actually, for cells with grid[i][j]==1, all four lengths are at least 1, so min>=1. So we can just compute for all cells: total += max(0, min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1). But if any is 0 (which only happens if grid[i][j]==0 because if grid[i][j]==1, UL[i][j] would be at least 1), but if grid[i][j]==0, UL[i][j]=0, etc. So we can safely sum min(...)-1 for all cells and then add max(0,...). But it's simpler to check grid[i][j]==1.
Now, is this counting each X shape exactly once? Let's test with a small grid.
Example: A 3x3 grid of all 1s. Then for center cell (1,1) (0-indexed), UL[1][1] = 2? Actually, compute:
UL:
(0,0):1
(0,1):1? UL[0][1] = 1 since no up-left.
(0,2):1
(1,0):1 (since no up-left)
(1,1): UL[1][1] = UL[0][0]+1 = 2
(1,2): UL[1][2] = UL[0][1]+1 = 2? Actually UL[0][1]=1, so UL[1][2]=2.
(2,0):1
(2,1): UL[2][1] = UL[1][0]+1 = 2
(2,2): UL[2][2] = UL[1][1]+1 = 3
UR:
(0,0):1 (since no up-right? Actually for (0,0), up-right would be? i>0 and j<cols-1 not satisfied, so UR[0][0]=1)
(0,1): UR[0][1] = 1 (since i=0 no up)
(0,2):1? Actually for (0,2), j=2 is last column, so UR[0][2]=1.
(1,0): UR[1][0] = 1? i>0 yes, but j+1=1 within bounds, UR[0][1]=1, so UR[1][0]=1+1=2? Wait, compute: UR[i][j] = grid[i][j]==1? 1 + UR[i-1][j+1] if i>0 and j<n-1 else 1. So for (1,0): i=1>0, j=0, j+1=1<n? yes. So UR[1][0] = 1 + UR[0][1] = 1+1=2.
(1,1): i=1>0, j=1, j+1=2, UR[0][2]=1 => 2.
(1,2): i>0, j=2, j+1=3 out of bounds, so just 1? Actually, condition: if i>0 and j<n-1, else 1. Here j=2, n-1=2, j<n-1 false, so UR[1][2]=1.
(2,0): i=2>0, j=0, j+1=1, UR[1][1]=2 => 3.
(2,1): i=2>0, j=1, j+1=2, UR[1][2]=1 => 2.
(2,2): i=2>0, j=2, j+1 out, so 1.
DL:
Compute from bottom up. We'll do: DL[i][j] = if grid[i][j]==1 then 1 + DL[i+1][j-1] if i0 else 1.
So for i=2 down to 0.
i=2, j=0: grid[2][0]=1, i<m-1? m=3, i=2 is last, so no i+1 -> DL[2][0]=1.
j=1: DL[2][1] = 1 + DL[3][0]? i=2<m-1? false (2<2 false), so just 1.
j=2: similarly 1.
i=1, j=0: i=1<m-1? 1<2 true, j>0? false (j=0), so DL[1][0]=1.
j=1: i=1<m-1 true, j=1>0 true, DL[2][0] = 1 => DL[1][1]=1+1=2.
j=2: j>0 true, i=1<m-1 true, DL[2][1]=1 => DL[1][2]=2.
i=0, j=0: i=0<m-1 true, j=0>0 false => DL[0][0]=1.
j=1: i=0<m-1 true, j=1>0 true, DL[1][0]=1 => DL[0][1]=2.
j=2: i=0<m-1 true, j=2>0 true, DL[1][1]=2 => DL[0][2]=3.
DR:
DR[i][j] = if grid[i][j]==1 then 1 + DR[i+1][j+1] if i<m-1 and j<n-1 else 1.
Compute i from bottom up, j from right to left? Actually we need to ensure i+1,j+1 computed before i,j. So we iterate i from m-1 down to 0, and for each i, j from n-1 down to 0.
i=2:
j=2: i=2 last row, j=2 last col => DR[2][2]=1.
j=1: j=1<n-1 true, i=2<m-1 false => no i+1, so just 1.
j=0: similarly 1.
i=1:
j=2: i=1<m-1 true, j=2<n-1 false => 1.
j=1: i=1<m-1 true, j=1<n-1 true, DR[2][2]=1 => DR[1][1]=2.
j=0: i=1<m-1 true, j=0<n-1 true, DR[2][1]=1 => DR[1][0]=2.
i=0:
j=2: i=0<m-1 true, j=2<n-1 false => 1.
j=1: i=0<m-1 true, j=1<n-1 true, DR[1][2]=1? Actually DR[1][2] we computed as 1 => DR[0][1]=2.
j=0: i=0<m-1 true, j=0<n-1 true, DR[1][1]=2 => DR[0][0]=3.
Now compute min at each cell and sum L = min(...)-1.
Total = 1. So there is exactly one X shape (center at (1,1) with arm length 1). That matches the 3x3 all-ones grid: it contains one X shape of arm length 1 (the 5 cells: center and four diagonals). But does it also contain an X shape of arm length 2? No because arm length 2 would require cells (i-2,j-2) etc, but grid is only 3x3, so arm length 2 would need cells at ( -1,-1) which are out of bounds. So only one.
Now if we had a larger grid with all 1s, say 5x5. Then for the center (2,2), UL[2][2] would be 3? Let's compute roughly: UL at (2,2): path from (0,0) to (2,2) is 3 cells, so UL=3. UR: from (0,4) to (2,2): but we need successive: (0,4) to (1,3) to (2,2) -> that's 3 cells, so UR[2][2]=3. DL: from (2,2) to (4,0): actually down-left: (2,2), (3,1), (4,0) -> 3 cells, so DL=3. DR: (2,2),(3,3),(4,4)->3. So min=3, L=2. So center (2,2) would have L=2, contributing 2 X shapes: arm lengths 1 and 2. Also other centers: for example (1,1) in 5x5? UL[1][1]=2, UR[1][1]=2? Actually (1,1) up-right: (0,2) to (1,1): 2 cells => UR=2; down-left: (1,1),(2,0) maybe 2; down-right: (1,1),(2,2) 2; UL:2. So min=2, L=1. So (1,1) contributes 1. Similarly (2,1) etc? But we need to compute all. In a full 5x5 of 1s, how many X shapes? Total would be sum over cells of (min(4 diagonal lengths)-1). For interior cells, it will vary. This seems plausible.
Thus, the algorithm is straightforward.
Now we need to write a function. The input is a 2D grid of integers. It might be a list of lists. We'll assume it's 0/1 only? Possibly there could be other integers? But problem says "X-shapes" of 1's, so we treat non-1 as 0? Or we treat any non-zero as 1? Typically grid of integers might have values 0 and 1. We'll assume binary.
Edge cases: empty grid, grid with no 1s, small grid (1x1, 2x2 etc). Our algorithm handles.
Complexity: O(mn) time, O(mn) space for the four arrays (or we can do it in place with less space if we modify grid? But need original for calculations? We could compute using four separate arrays or reuse? We'll just use four arrays for clarity. That's 4mn integer space, which is okay for typical constraints. If m,n up to 1000, that's 4 million integers, okay. Could also compute on the fly with two passes and accumulate? Might be possible but more complex.
Alternatively, we can compute UL and UR in one pass, then compute DL and DR in another pass and in the second loop sum contributions to avoid storing all four? But we need all four values simultaneously. Could compute UL and UR first store. Then compute DL and DR and at the same time for each cell compute min and add to total. But we need UL and UR for that cell already computed. That's possible: we compute UL and UR and keep them. Then when computing DL and DR in reverse pass, we can compute min(UL[i][j], UR[i][j], current DL, current DR) -1 and add. That would require storing UL and UR (two arrays) and while computing DL and DR we can compute the sum. But we still need DR and DL. Actually we can compute DL and DR one cell at a time. In the reverse iteration, we compute DL[i][j] and DR[i][j] (each depends on neighbors which have been computed earlier in the reverse pass). So we can compute DL[i][j] and DR[i][j] for each cell, then compute L = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1, add to total if grid[i][j]==1. That uses two arrays UL and UR plus temporary for DL and DR? But we need to store UL and UR for all cells; DL and DR are computed on the fly. We could also avoid storing DL and DR separately? Actually we need to compute them for each cell, but we can compute them and then use them immediately, we don't need to store them for later because they are only used at that cell. So we can have two 2D arrays for UL and UR, and then in the reverse pass we compute DL and DR on the fly using variables? But to compute DL[i][j], we need DL[i+1][j-1] which might have been computed in a previous step (i+1, j-1). Since we iterate i decreasing and for each i we iterate j increasing? For DL: we need i+1 (row below) and j-1 (left). So if we iterate i from bottom to top, and for each i we iterate j from 0 to n-1 (increasing), then when computing DL[i][j], we need DL[i+1][j-1] which would be from the next row (i+1) and column j-1. Since i+1 > i, and we are going decreasing i, the row i+1 has already been processed. For j, if we iterate j increasing, then j-1 is less than j, so it's already computed for the same row i? Actually for DL[i][j], we need DL[i+1][j-1] which is from a different row i+1 and column j-1. Since row i+1 is fully processed when we processed that row earlier (because we go i decreasing), we can have stored the entire row i+1 values in an array. So we need to keep the previous row's DL values. Similarly, for DR we need DR[i+1][j+1], which is from row i+1 and column j+1; if we iterate j from right to left, we could use previously computed values in same row? But we could just store the entire DL and DR matrices as we compute. Or we can compute all four separately. Simpler: compute all four and store. It's acceptable.
We'll implement straightforward: allocate 2D lists for each.
Now we need to write the function. Let's define:
def count_x_shapes(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
# initialize arrays with zeros
UL = [[0]*n for _ in range(m)]
UR = [[0]*n for _ in range(m)]
DL = [[0]*n for _ in range(m)]
DR = [[0]*n for _ in range(m)]
# compute UL
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
UL[i][j] = 1
if i>0 and j>0:
UL[i][j] += UL[i-1][j-1]
# else remains 0
# compute UR
for i in range(m):
for j in range(n-1, -1, -1):
if grid[i][j] == 1:
UR[i][j] = 1
if i>0 and j < n-1:
UR[i][j] += UR[i-1][j+1]
# compute DL
for i in range(m-1, -1, -1):
for j in range(n):
if grid[i][j] == 1:
DL[i][j] = 1
if i < m-1 and j > 0:
DL[i][j] += DL[i+1][j-1]
# compute DR
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if grid[i][j] == 1:
DR[i][j] = 1
if i < m-1 and j < n-1:
DR[i][j] += DR[i+1][j+1]
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
L = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1
if L > 0:
total += L
return total
But wait: In this computation, UL[i][j] counts the total length of consecutive 1s ending at (i,j) along up-left. That includes the cell itself. So for arm length k, we need UL[i][j] >= k+1. The max k = UL[i][j]-1. That's correct. But careful: For UL, we added 1 plus UL[i-1][j-1] if exists. That's correct.
Now test with the 3x3 all-1s: we computed UL, etc manually and got total=1. That matches.
Now test with a 5x5 all-1s. Let's compute roughly: For center (2,2): UL=3, UR=3, DL=3, DR=3 => min=3 => L=2 => contributes 2.
For cells at distance 1 from center: e.g., (1,1): UL=2, UR=2? Let's compute UL[1][1] = UL[0][0]+1 = 2; UR[1][1] = UR[0][2]+1? Actually for (1,1), UR: i=1>0, j=1, j+1=2, UR[0][2]? UR[0][2] we compute: UR[0][2] = 1 (since i=0) => UR[1][1] = 1+1=2. DL[1][1] = 1+DL[2][0]; DL[2][0] = 1 (since i=2 last row) => DL[1][1]=2. DR[1][1] = 1+DR[2][2]; DR[2][2]=? bottom row, last col =>1 => DR[1][1]=2. So min=2 => L=1. Similarly (1,2): UL[1][2]=2, UR[1][2]? For (1,2), UR: i=1>0, j=2<n-1? n=5, n-1=4, j=2<4 true, so UR[0][3]? But need to compute entire matrix. Let's not manually, but likely (1,2) will have min=2? Actually, (1,2) is not symmetric? It might have UL=2 (from (0,1) and (1,2)), UR=2? Let's compute: UL: from (0,1) to (1,2): UL[0][1]=1, so UL[1][2]=2. UR: for (1,2), need UR[0][3]? But UR[0][3] we haven't computed. For 5x5, UL and UR will be such that many cells will have min>=2? Actually, the pattern: For a full grid of 1s, the UL[i][j] = min(i+1, j+1)? Actually, UL[i][j] = min(i+1, j+1)? Because it's the number of steps from the top-left corner? For a grid of all 1s, UL[i][j] = min(i+1, j+1) because it's the length of diagonal from (i-k,j-k) until either row or column starts. More precisely, UL[i][j] = min(i+1, j+1). Because if you start from (i,j) and go up-left, you can go until row 0 or column 0. So the count is min(i,j)+1? Actually, i and j are zero-indexed. The number of cells including (i,j) along up-left diagonal is min(i,j)+1? For example, (2,2): min(2,2)+1=3. (1,2): min(1,2)+1=2. Yes. Similarly, UR[i][j] = min(i+1, n-j)? Because up-right diagonal goes to top or right edge. UR[i][j] = min(i+1, n-j). For (1,2) in 5x5: i+1=2, n-j=5-2=3, min=2 => UR=2. DL[i][j] = min(m-i, j+1). For (1,2): m-i=5-1=4, j+1=3, min=3? Wait, DL: down-left, goes down until bottom row, left until column 0. So number of cells = min(m-i, j+1). (1,2): m-i=4, j+1=3 => 3. But is that correct? Let's compute: from (1,2) down-left: (1,2), (2,1), (3,0) => that's 3 cells if grid is all 1s. So DL=3. DR[i][j] = min(m-i, n-j). For (1,2): m-i=4, n-j=3 => 3. So min of (2,2,3,3) = 2 => L=1. So (1,2) contributes 1. Similarly (2,1) same. (2,2) we did. (2,0) maybe? (2,0): UL: min(2,0)+1 = 1; UR: min(2+1, n-0=5) => min(3,5)=3; DL: min(m-i=3, j+1=1)=1; DR: min(3,5)=3? Actually, DR: min(m-i, n-j) = min(5-2=3,5-0=5)=3. min(1,3,1,3)=1 => L=0. So not all interior cells contribute. So total count in 5x5 all-1s will be sum over cells of (min( four lengths ) - 1). That sum can be computed analytically but it's fine.
Thus algorithm counts all X shapes.
Now, what about overlapping shapes? For a large X of arm length 2, it contains an X of arm length 1 centered at same center, but those are separate shapes and counted separately. That seems typical: counting all X shapes of all sizes.
Now is there any other interpretation? Possibly they only want to count the number of X shapes as connected components that are X-shaped. That would be something like: perform DFS to find connected components of 1s, then for each component, check if it forms an X shape. But then we'd need to define X shape exactly. That is more complicated and ambiguous. The diagonal DP approach is clean and efficient.
Given that the problem says "Write a function to find the number of 'X-shapes' of 1's", it's likely they refer to this known problem.
Thus I'll produce solution with DP counting all X shapes (each center and arm length combination). Provide explanation.
But let's be thorough: Could there be X shapes that are not centered at a cell? In the pattern we described, the X shape is always centered at a cell (grid point). In an odd-sized X, the center is a cell. That's natural.
Also note: The minimal X requires at least 3x3 area. So on a grid smaller than 3x3, answer 0.
Now, we need to write code in a language? Probably Python. We'll write a function count_x_shapes(grid). Input: list of lists of integers. Output: integer.
We'll also include error handling.
Now, we need to explain algorithm: Use dynamic programming to precompute lengths of consecutive 1s along four diagonal directions for each cell. Then for each cell, the number of X shapes centered at that cell is the minimum of those four lengths minus one (since the center is counted in each). Summing gives total count.
Let's produce a detailed explanation:
We define UL[i][j] as the number of consecutive 1s ending at (i,j) in the up-left direction (i.e., along the diagonal from top-left to bottom-right). Similarly UR, DL, DR. These can be computed with DP in O(mn) time.
For any cell (i,j) that is 1, the largest arm length L_max such that an X shape of arm length L exists centered at (i,j) is limited by the shortest arm among the four diagonals. Since each diagonal arm of length L requires L+1 consecutive cells (including center) along that direction, we have L_max = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1. If L_max >= 1, then there exist L_max distinct X shapes centered at (i,j) with arm lengths 1,2,...,L_max. So the contribution of (i,j) to the total count is L_max.
Summing over all cells yields the total number of X shapes.
Complexity: O(mn) time, O(mn) space.
Edge Cases: Empty grid returns 0.
We'll also provide a small test.
Now, ensure we handle grid values not 0/1? Possibly we treat any non-zero as 1? But problem says "1's", so we expect grid contains integers, but we specifically look for 1. We'll check grid[i][j] == 1.
Potential pitfalls: When computing DL and DR, careful with bounds. Our loops as described are fine.
Now, we can also think about optimizing space: Could we compute UL and UR and store them, then compute DL and DR on the fly? But that's minor.
I'll write code accordingly.
But we must consider that UL[i][j] etc can be large. But that's okay.
Now, what about the case where the grid has 1s but not forming full X due to missing some cells? Our DP ensures only continuous diagonals are counted.
Test with a grid that has isolated 1s: no X shapes.
Test with a grid:
1 0 1
0 1 0
1 0 1
That's a 3x3 with X shape of arm length 1. Let's compute:
UR:
(0,0):1 (since i=0)
(0,1):0? grid[0][1]=0 =>0
(0,2):1
(1,0):0? grid[1][0]=0 =>0
(1,1): grid[1][1]=1, UR[0][2]=1 => UR[1][1]=2? Actually, if grid[1][1]==1, and i>0 and j<n-1? j=1<n-1=2 true, so UR[1][1]=1+UR[0][2]=2.
(1,2):0? grid[1][2]=0 =>0
(2,0):1? grid[2][0]=1, i=2>0, j=0, j+1=1? but j<n-1? 0<2 true, so need UR[1][1]=2 => but wait, we compute UR from top to bottom. For (2,0): i=2>0, j=0, j+1=1<n-1? yes, so UR[2][0] = 1 + UR[1][1]? But careful: we are iterating i increasing, j decreasing. At i=2, j=0, we need UR[1][1] which has been computed at i=1, j=1. That's fine. So UR[2][0] = 1 + 2 = 3? But grid[2][0] is 1. So UR[2][0]=3. However, does that make sense? UR direction from (2,0) goes up-right: cells (2,0), (1,1), (0,2). Indeed all 1s, so length=3. So correct.
(2,1):0? grid[2][1]=0 =>0
(2,2):1? grid[2][2]=1, i=2>0, j=2, j+1 out => UR[2][2]=1
DL:
compute i from 2 down to 0.
(2,0):1
(2,1):0
(2,2):1
(1,0):0? grid[1][0]=0 =>0
(1,1): grid[1][1]=1, i=1<2, j=1>0, DL[2][0]=1 => DL[1][1]=2
(1,2):0? grid[1][2]=0 =>0
(0,0):1? grid[0][0]=1, i=0<2, j=0>0 false => DL[0][0]=1
(0,1):0? grid[0][1]=0 =>0
(0,2):1? grid[0][2]=1, i=0<2, j=2>0 true, DL[1][1]=2 => DL[0][2]=3? Actually, from (0,2) down-left: (0,2), (1,1), (2,0) -> all 1s, so length=3. Yes.
DR:
(2,2):1
(2,1):0
(2,0):1
(1,2):0? grid[1][2]=0 =>0
(1,1): grid[1][1]=1, i=1<2, j=1<2, DR[2][2]=1 => DR[1][1]=2
(1,0):0? grid[1][0]=0 =>0
(0,2):1? grid[0][2]=1, i=0<2, j=2<2 false => DR[0][2]=1? Actually j=2, n-1=2, j<n-1 false, so DR[0][2]=1. But down-right from (0,2): (0,2), (1,3) out of bound, so length=1, correct.
(0,1):0? grid[0][1]=0 =>0
(0,0):1? grid[0][0]=1, i=0<2, j=0<2 true, DR[1][1]=2 => DR[0][0]=3? Actually down-right from (0,0): (0,0),(1,1),(2,2) all 1s => length=3. So DR[0][0]=3.
Total = 1. So count=1. That matches expectation: there is exactly one X shape (the classic X). Good.
Now test with a grid that has two separate X shapes. For example, a 5x5 with two separate X patterns not overlapping. We can design: two Xs at different locations. The sum should count both.
Thus algorithm seems correct.
Now consider if there are 1s that form an X shape but also have extra 1s attached to arms? That might create multiple X shapes centered at the same cell? Actually, extra 1s attached to the arms (like the arms extend further but not symmetrically) could limit the arm length because one direction might be shorter. But if arms are longer in some directions but not others, the min determines the maximum symmetric arm. That's correct for X shape: we need all four directions to have the same length. So an X shape requires symmetric arms. So if one direction is longer, we can still have X shapes up to the shortest arm. So extra 1s beyond the shortest don't contribute to additional symmetric X shapes because you need all four directions equally. However, if one direction is longer, we could have an X shape with arm length equal to the shortest side, and then the longer direction might have additional shapes centered at other cells? Possibly. That's fine.
Now, is there a scenario where an X shape exists but the center is not a cell? For example, an X shape of even size? But typical X shapes have odd dimensions and a central cell. If we had arm length 1, it's 3x3, central cell. For arm length 2, it's 5x5, central cell. So center is always a cell. So fine.
Thus, I'm confident this is the intended solution.
Now we need to produce the answer: Provide the algorithm explanation and then code.
We might want to optimize by using only two arrays for UL and UR and then computing DL and DR on the fly and summing. But for clarity, we'll compute all four.
We also need to handle large grids efficiently. Python recursion not needed.
Potential memory optimization: we could use the input grid to store UL? But not necessary.
Let's produce final solution.
Now, the function signature: def count_x_shapes(grid: List[List[int]]) -> int.
We'll include imports if needed.
Now, produce explanation.
We'll also discuss time and space complexity.
Now, final answer.
We are given a 2D grid of integers (0s and 1s). We need to count the number of X‑shapes formed by 1s. An X‑shape is defined by a center cell (i, j) and an arm length k ≥ 1 such that the following 4·k cells are all 1:
(i−t, j−t) (up‑left)
(i−t, j+t) (up‑right)
(i+t, j−t) (down‑left)
(i+t, j+t) (down‑right)
for every t = 1 … k. The center itself must be 1.
If a center can support arm lengths 1,2,…,L_max, it contributes L_max distinct X‑shapes. The total answer is the sum of these contributions over all cells.
The solution uses four dynamic‑programming tables that store, for each cell, the length of the longest contiguous segment of 1s in each diagonal direction ending at that cell. With these tables we can compute the maximal possible arm length for every center in constant time.
Algorithm
Pre‑compute the four diagonal length tables
UL[i][j] – up‑left (↖) length ending at (i,j) UL[i][j] = 1 + UL[i-1][j-1] if grid[i][j]==1 and i>0,j>0, otherwise 1 if grid[i][j]==1.
UR[i][j] – up‑right (↗) length ending at (i,j) UR[i][j] = 1 + UR[i-1][j+1] if grid[i][j]==1 and i>0,j < n-1.
DL[i][j] – down‑left (↙) length ending at (i,j)
Computed by iterating rows from bottom to top: DL[i][j] = 1 + DL[i+1][j-1] if grid[i][j]==1 and i<m-1,j>0.
DR[i][j] – down‑right (↘) length ending at (i,j)
Computed by iterating rows from bottom to top and columns from right to left: DR[i][j] = 1 + DR[i+1][j+1] if grid[i][j]==1 and i<m-1,j<n-1.
Count X‑shapes
For every cell (i,j) with grid[i][j]==1 compute L = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1
(subtract 1 because the center itself is counted in each direction). L is exactly the number of X‑shapes centered at that cell. Add L to the total.
Return the total.
Correctness Proof
We prove that the algorithm returns the exact number of X‑shapes.
Lemma 1
For any cell (i,j), UL[i][j] equals the number of consecutive 1s on the up‑left diagonal ending at (i,j) (including (i,j)). Proof. By definition, if grid[i][j]==0 then UL[i][j]=0. If it is 1, we add 1 to the value from the previous cell (i-1,j-1) (if it exists). This recurrence exactly counts the length of the contiguous block of 1s along that diagonal. ∎
Lemma 2
Analogous statements hold for UR, DL, and DR.
Lemma 3
For a fixed center (i,j) that is 1, the largest arm length k for which an X‑shape exists is k_max = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1. Proof. To have an arm of length k in a given direction, we need k cells beyond the center plus the center itself, i.e. at least k+1 consecutive 1s along that diagonal, ending at the center. By Lemma 1 and Lemma 2 the lengths UL[i][j], etc., give exactly that number. Hence each direction imposes the constraint k ≤ that_length - 1. The maximal feasible k is the minimum of these four upper bounds, minus one. ∎
Lemma 4
If L = min(...)-1 for a cell, then there exist exactly L distinct X‑shapes centered at that cell (with arm lengths 1,2,…,L). Proof. For each k from 1 to L, the condition of Lemma 3 guarantees that all required cells are 1, so an X‑shape of arm length k exists. For k = L+1 at least one direction fails, so no larger X‑shape exists. Thus precisely L X‑shapes are centered at (i,j). ∎
Theorem
The algorithm’s total sum equals the total number of X‑shapes in the grid. Proof. By Lemma 4, for every cell (i,j) we add exactly the number of X‑shapes that have that cell as their center. Since every X‑shape has a unique center (the intersection of its two diagonals), the contributions are disjoint and cover all X‑shapes. Summing over all cells therefore yields the exact count. ∎
Complexity Analysis
We perform four passes over the grid to fill the DP tables, each in O(m·n) time. The final pass also takes O(m·n) time. Total time complexity: O(m·n).
We store four auxiliary m×n integer tables, requiring O(m·n) extra space. (By computing two tables on‑the‑fly the space can be reduced, but the problem constraints usually allow this straightforward approach.)
Reference Implementation (Python)
python
def count_x_shapes(grid):
"""
Count the number of X-shapes formed by 1's in a 2D grid.
An X-shape has a center cell (i,j) and arm length k>=1 such that
all cells (i±t, j±t) for t=1..k are 1.
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
# Initialize DP tables
UL = [[0]*n for _ in range(m)]
UR = [[0]*n for _ in range(m)]
DL = [[0]*n for _ in range(m)]
DR = [[0]*n for _ in range(m)]
# Up-left: UL[i][j] depends on UL[i-1][j-1]
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
UL[i][j] = 1
if i > 0 and j > 0:
UL[i][j] += UL[i-1][j-1]
# Up-right: UR[i][j] depends on UR[i-1][j+1]
for i in range(m):
for j in range(n-1, -1, -1):
if grid[i][j] == 1:
UR[i][j] = 1
if i > 0 and j < n-1:
UR[i][j] += UR[i-1][j+1]
# Down-left: DL[i][j] depends on DL[i+1][j-1]
for i in range(m-1, -1, -1):
for j in range(n):
if grid[i][j] == 1:
DL[i][j] = 1
if i < m-1 and j > 0:
DL[i][j] += DL[i+1][j-1]
# Down-right: DR[i][j] depends on DR[i+1][j+1]
for i in range(m-1, -1, -1):
for j in range(n-1, -1, -1):
if grid[i][j] == 1:
DR[i][j] = 1
if i < m-1 and j < n-1:
DR[i][j] += DR[i+1][j+1]
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
# maximum arm length for this center
L = min(UL[i][j], UR[i][j], DL[i][j], DR[i][j]) - 1
if L > 0:
total += L
return total