We are given a 2D grid of integers. We need to find the number of "T-shapes" of 1's. The problem statement does not explicitly define what a T-shape is. Typically, in grid problems, a T-shape might be a pattern of 1's that looks like the letter T. But we need to clarify.
Common T-shape definitions in matrix contexts:
- Sometimes it's a cross: a center cell and its four neighbors (up, down, left, right). But that's a plus shape, not T.
- A T-shape could be three cells in a row and one cell below the middle, forming a T. That is typical for tetrominoes: the T-tetromino consists of four cells: three in a line and one attached to the center of that line, perpendicular to it. So it's like:
But it can be rotated in four orientations: upright T (three horizontal on top, one below center), upside-down T (three horizontal on bottom, one above center), left-facing T (three vertical on left, one to the right of center), right-facing T (three vertical on right, one to the left of center). But the problem says "T-shapes" of 1's. Possibly they mean exactly that: four connected cells forming a T pattern. However, it says "number of T-shapes", so we are counting occurrences of that pattern.
But also, the grid contains integers, but we care about 1's. So we consider cells with value 1.
Alternatively, a T-shape might be defined differently: for example, a center cell with three neighbors in a T configuration? That would be a plus minus one arm? Actually, a T has three arms: top, left, right? That would be a cross missing one arm. So a T could be a cell with three adjacent cells in the shape of T: for example, a central cell with neighbors: up, left, right (forming a T upright), or down, left, right (inverted), etc. That would be four cells as well. That is essentially the T-tetromino but missing one cell? Wait: In the T-tetromino, there are four cells. If we consider the central cell as the intersection point, then we have three arms: up, left, right? Actually, in an upright T: the horizontal bar is the top three cells? Or the vertical bar? Let's clarify:
The T-tetromino can be represented as:
A A A
A
But that is 4 cells: positions (0,0), (0,1), (0,2), (1,1). So the intersection is at (0,1)? Actually, if we think of the T upright, the stem is below the crossbar. So the center of the T could be at (0,1) if we consider the crossbar as three cells horizontally. But (0,1) has neighbors: left (0,0), right (0,2), down (1,1). That's three neighbors. So indeed, an upright T has a central cell with three neighbors: left, right, and down. Similarly, inverted T: central cell has left, right, up. Left-facing T: central cell has up, down, right? Wait, left-facing T: the vertical bar is three cells? Actually, for left-facing: the stem points left. Pattern:
A
A A A
But that's oriented differently. Let's define rotations:
- T1: (0,1), (1,0), (1,1), (1,2) -> This is an inverted T? Actually, that pattern: (0,1) is above the middle of a horizontal bar at row1: (1,0),(1,1),(1,2). So that's an upside-down T (stem up). The central cell is at (1,1) with neighbors: up (0,1), left (1,0), right (1,2). So central cell has three neighbors: up, left, right.
- T2: (0,0), (0,1), (0,2), (1,1) -> upright T: stem down. Central cell at (0,1) has neighbors: left (0,0), right (0,2), down (1,1).
- T3: (0,0), (1,0), (1,1), (2,0) -> left-facing? Actually, pattern: (0,0) above, (1,0) middle, (1,1) right, (2,0) below? That's a T rotated 90° clockwise? Let's systematically derive all four rotations of the T-tetromino:
Standard T-tetromino (upright):
positions: (0,0), (0,1), (0,2), (1,1) // assuming a 2x3 bounding box.
But we can also place it in other orientations.
Rotate 90° clockwise: (0,1), (1,1), (2,1), (1,0). That's a T pointing right: stem to the right. Central cell? Which cell is the center? It could be (1,1) with neighbors: up (0,1), down (2,1), left (1,0). So central cell has three neighbors: up, down, left.
Rotate 180°: (0,1), (1,0), (1,1), (1,2) as we had. That's inverted T (stem up). Central cell (1,1) with neighbors: up (0,1), left (1,0), right (1,2).
Rotate 270°: (0,1), (1,1), (2,1), (1,2). That's T pointing left: stem to the left. Central cell (1,1) with neighbors: up (0,1), down (2,1), right (1,2).
Thus, all four T-tetrominoes consist of a central cell (the one that has three neighbors within the T) and three adjacent cells in the shape of a T. So in each orientation, there is exactly one cell that is adjacent to the other three (the intersection). That cell has exactly three neighbors that are part of the T. However, note that in the T-tetromino, the central cell might have degree 3 (if we consider only the T's connectivity) but also might have other neighbors in the grid that are not part of the T. But we are only counting patterns of 1's that form a T-shape. The pattern must consist of exactly four cells? Or could it be larger? Typically, "T-shape" might refer to exactly that tetromino.
But the problem statement is brief: "find the number of 'T-shapes' of 1s." It doesn't specify size. Could it be that a T-shape is defined as a plus shape but missing one arm? That is exactly the T-tetromino. So we assume we are counting occurrences of 4-cell patterns that form a T.
But also, the grid may have overlapping T-shapes? Usually we count each distinct set of cells that form a T. But if T shapes overlap, they might share cells. We need to count each occurrence? Possibly each distinct T pattern, even if overlapping. But careful: if we have a plus shape (5 cells), it contains multiple T's? For instance, a cross with all five 1's contains four different T's? Because if you take any arm away you get a T? But the definition likely expects exactly four cells forming a T. So if there is a plus shape, there are multiple T's? But the plus shape has 5 cells; each subset of 4 cells that form a T? Actually, the plus shape is like:
(i-1,j)
(i,j-1) (i,j) (i,j+1)
(i+1,j)
If we remove one arm, we get a T. So there are four T's: remove top, remove bottom, remove left, remove right. But each T would consist of four cells. However, the T pattern requires exactly three arms? The plus shape is not a T; it's a plus. But if we have a plus shape, it contains four different T-shapes (each missing one arm). But are those T-shapes considered present? Possibly yes, because they are subpatterns of 1's. But the problem might ask to count all T-shapes, meaning any set of four cells that form a T pattern. But then a plus shape would contribute 4. But is that intended? The problem statement doesn't specify that the T-shape must be maximal or isolated. Usually such problems count each distinct occurrence of the shape, even overlapping. But we need to be cautious.
Alternatively, the problem might define a T-shape as a specific arrangement of exactly three 1's? That seems unlikely.
Given no further details, I'll assume the T-tetromino pattern: exactly four 1's arranged in one of the four orientations. And we count each such pattern. Overlapping patterns count separately. That is, every set of four cells that match one of the T patterns, regardless of whether additional 1's are adjacent, counts as a T-shape. So if there is a plus shape, we would count four T's.
But wait: the T-tetromino has a specific shape: three cells in a line (the crossbar) and one cell attached to the middle of that line, perpendicular. In the upright T, the crossbar is horizontal (three cells in a row) and the stem is below the center. So the shape is not symmetric; there is a specific cell that is the "center" of the T (the one that connects to three others). In a plus shape, if we take the central cell, it has four neighbors. If we take any of the four arms as the center? Actually, in a plus shape, the central cell has four neighbors. If we consider a T pattern, we need exactly three neighbors for the central cell within the pattern. But if we have a plus shape, and we pick a subset that forms a T, we would be selecting three of the four arms plus the central cell? That would be four cells: central and three arms. That is indeed a T (with the central cell being the intersection and the three arms being the crossbar? Wait, careful: In the T pattern, the central cell is not necessarily the one with three neighbors? In the T-tetromino, there is one cell that is adjacent to the other three. In the upright T, the central cell is at the intersection of the crossbar and the stem? Actually, in upright T: positions: (i,j), (i,j-1), (i,j+1), (i+1,j). The central cell is at (i,j) if we consider it as the cell that has left, right, and down neighbors. But note that (i,j) also has up neighbor? Possibly not if there is no plus shape. In a pure T, (i,j) has exactly three adjacent cells within the pattern: left, right, down. So it has degree 3. The other cells have degree 1 (the ends of the crossbar) and the stem has degree 1 (the bottom cell) except that the stem (i+1,j) is only connected to (i,j). So indeed the central cell is the only one with three connections.
In a plus shape, the central cell has four neighbors. If we consider a subset of four cells that includes the central cell and three of the four arms, that subset would have the central cell with three neighbors (the three arms) and each arm has degree 1. That is exactly a T pattern. So yes, a plus shape yields four distinct T patterns (by omitting one arm). But each T pattern uses the central cell and three arms. So if we count all T patterns, a plus shape would contribute 4. That seems plausible.
But maybe the problem expects to count only maximal T-shapes or isolated ones? The statement is ambiguous. However, typical coding interview questions about counting shapes in a grid (like counting connected components, patterns, etc.) often count each occurrence of a specific pattern, even if overlapping. For example, counting "X" shapes or "T" shapes in a binary matrix. They often define the shape explicitly and ask to count how many times it appears. Overlapping counts are allowed unless stated otherwise. But sometimes they want distinct shapes that do not share cells. But that would be a packing problem, more complex. Since it's not specified, I'll assume we count every occurrence of the T pattern, meaning every set of four cells that match the pattern exactly, regardless of whether those cells are part of a larger shape. But we must be careful: if there are extra 1's around, it's still a T if the four cells are 1 and arranged in T shape. But if there is an extra 1 that breaks the pattern? Actually, we are only looking for patterns of 1's. So if we have a T pattern, we count it regardless of other 1's nearby. So overlapping is allowed: the same cell can be part of multiple T patterns.
Thus, we need to detect all positions in the grid that serve as the "center" of a T? Actually, in each T pattern, there is a unique central cell (the one with three neighbors within the pattern). However, note that in the T shape, the central cell is not necessarily the exact geometric center if we consider the shape's bounding box? But we can identify the central cell as the one that has exactly three adjacent cells that are part of the pattern and are placed in a T configuration. Alternatively, we can slide a window of 3x3 or 2x3 etc. and check for the pattern.
Better approach: iterate over all possible placements of the T-tetromino. There are four orientations. For each orientation, we can check at every possible anchor point if the pattern matches.
We need to define the shape relative to an anchor. Common approach: define each orientation by a set of relative coordinates from a reference cell (like the top-left of the bounding box). But we can also define by a central cell and the three neighbor offsets.
Option 1: define each orientation by a list of four (dx,dy) positions relative to a base cell (like the top-left corner of the bounding box). Then slide over grid positions where the bounding box fits.
Option 2: use the central cell approach: for each cell (i,j) that could be the central cell, check if it and three of its neighbors form a T. But the central cell must have exactly three of the four possible directions occupied? Actually, the T shape in any orientation consists of a central cell and three adjacent cells in specific directions. For upright T: the three neighbors are left, right, down. For inverted: left, right, up. For left-facing: up, down, right? Wait, we need to be consistent. Let's define directions as: up (-1,0), down (1,0), left (0,-1), right (0,1). Then the T orientations correspond to sets of three directions that are perpendicular, i.e., one direction opposite to another? Actually, the three arms: two are opposite (like left and right) and one is perpendicular (like up or down). Or it could be two are opposite (up and down) and one is perpendicular (left or right). So the three directions must consist of a pair of opposite directions and one of the two perpendicular directions. That yields four combinations: {left, right, down}, {left, right, up}, {up, down, right}, {up, down, left}. That's exactly the four T orientations.
Thus, we can treat the central cell as the intersection of the T. But is the central cell always the one that has three connections? In the T-tetromino, yes. However, could there be a T shape where the central cell is not the one with three connections? Consider the pattern: three cells in a line and one attached to the middle. The middle of the line is adjacent to both ends? Actually, the middle of the crossbar is adjacent to both ends and also the stem. So that's the central cell with three connections. The ends have one connection. So indeed the cell with degree 3 is unique. So we can count T-shapes by scanning for cells that have at least three neighbors that are 1, and then check if the pattern of those neighbors matches one of the T sets. But careful: a cell might have more than three neighbors that are 1, but we need exactly three that form the T pattern? Actually, if a cell has four neighbors (like a plus), then the set of its neighbors includes all four directions. We could still find T's by selecting subsets of three neighbors. But if we only look at the central cell and its immediate neighbors, we might count a T if we have three of the four directions present. But if we have all four, then that cell with all four neighbors would not be a central cell of a T? But we could still have T patterns using that central cell and any three of the four arms. That would be four T patterns with that central cell as center. So we should count those. So our approach of checking for every cell (i,j) as possible central cell: look at its four adjacent cells (up, down, left, right). If among them, exactly three are 1 and form a T? But we need to check that the three are in the correct configuration: they must include a pair of opposite directions and one perpendicular direction. But if exactly three are present, then automatically they satisfy: if three out of four directions are present, they either include both left and right (if the missing is up or down) or both up and down (if missing is left or right). Because if we have three directions, the only way to not include a pair of opposites is if we have, say, up, left, down? That includes up and down (opposites) and left. That's valid. Or up, left, right? That includes left and right (opposites) and up. That's valid. Or up, down, right? That's valid. Or left, down, right? That includes left and right? Actually, left, down, right: left and right are opposites, so valid. The only invalid combination would be if we had three directions that are all perpendicular? But there are only four directions; any three must include at least one pair of opposites? Let's check: possible sets of three from {U, D, L, R}:
- {U, D, L} -> contains U and D (opposites)
- {U, D, R} -> contains U and D
- {U, L, R} -> contains L and R
- {D, L, R} -> contains L and R
So indeed any three of the four includes a pair of opposites. So if we have exactly three neighbors that are 1, that automatically forms a T shape? But we must also consider that the three neighbors themselves may not be connected in a line? Actually, the shape we want: three arms: two opposite and one perpendicular. That's exactly what we get. So if a cell has exactly three adjacent cells that are 1 (and those three are in the directions that are present), then that set of four cells (center + three) forms a T shape. However, we must ensure that the three arms are exactly those cells and no extra ones? But the pattern only requires those four cells to be 1. If there are additional 1's elsewhere, that's fine. So if a cell has exactly three adjacent 1's, we count one T? But what if the cell has four adjacent 1's? Then we have more than three. But we can still form T shapes by omitting one arm. For each arm we omit, we get a T. So if a cell has all four neighbors 1, then there are four T's centered at that cell: for each missing direction (i.e., each arm we choose to omit), the three present arms form a T. But careful: if we have all four neighbors, then any subset of three of them yields a T. But are those T patterns distinct? They are distinct because they omit a different arm. But note: the central cell is the same, and the three neighbor cells differ. So each T pattern is a set of four cells: central cell + three specific neighbors. Since the neighbor sets differ, they are distinct T patterns. So we should count all such combinations.
Thus, we can count T-shapes by: For each cell (i,j) that is 1, consider the set of its orthogonal neighbors that are 1. Let k = number of such neighbors (0 to 4). Then the number of T-shapes that have (i,j) as the central cell is C(k,3) if we require exactly three arms? But wait: we need exactly three arms? The T shape requires three arms, but if we have four arms, we can choose any three to form a T. That gives C(4,3)=4 T's. If k=3, then C(3,3)=1 T. If k=2 or less, no T (since we need three arms). So total T's = sum over all cells of C(k,3). But is that always correct? Let's test with a plus shape: central cell has 4 neighbors => 4 T's. That matches our earlier reasoning. But what about a T shape itself? In a pure T, the central cell has exactly 3 neighbors, so it contributes 1. The other cells (the three arms) have only one neighbor (the central cell) so they contribute 0. So total T's = 1. Good.
But what about a shape that has a central cell with 3 neighbors, but those neighbors themselves are connected to others? That doesn't matter; we only care about the central cell and its immediate neighbors. So that counts one T.
But wait: are there T shapes where the central cell is not the cell with three connections? Could the T be oriented such that the central cell is not the one with three connections? In the T-tetromino, there is exactly one cell with three connections. So any T has a unique cell with degree 3 (within the set of four). So our method of counting via central cell covers all T's uniquely? Could the same T be counted multiple times? Possibly if a T has more than one cell that has three connections? In a T of four cells, only one cell has degree 3 (the intersection). The other three have degree 1. So no double counting. So each T corresponds to exactly one central cell (the one with three neighbors within the T). However, could there be a T pattern where the central cell has exactly three neighbors but those neighbors might also be connected to each other? In a T, the three arms are not connected to each other (except through the center). So the pattern is a tree with one node degree 3 and three leaves. So indeed the central cell is unique.
Thus, counting T-shapes reduces to: for each cell that is 1, count the number of its orthogonal neighbors that are 1, say k. Then the number of T's centered at that cell is binomial(k, 3). Sum over all cells.
But is that always correct? Let's think about edge cases: what if the T shape is on the border? The central cell must have three neighbors in the T. Those neighbors must be within grid bounds. Our method: for each cell, we check up/down/left/right. If the cell is on border, some directions are out of bounds, so we treat as 0. That's fine.
But what about T shapes that are rotated such that the central cell is not the one we think? For example, consider the T shape:
(0,0), (0,1), (0,2), (1,1). The central cell is (0,1) because it has left, right, down. That's clear. Our method would see cell (0,1) has neighbors: left (0,0)=1, right (0,2)=1, down (1,1)=1, up is out of bounds or 0. So k=3, binomial(3,3)=1. Good.
Now consider the T shape: (0,0), (1,0), (2,0), (1,1). That's left-facing? Actually, pattern: vertical bar: (0,0), (1,0), (2,0) and a stem to the right at (1,1). Which cell is central? The intersection is at (1,0)? But check neighbors: (1,0) has up (0,0), down (2,0), right (1,1). That's three neighbors. Left is maybe 0. So central cell is (1,0). So our method: for cell (1,0), we check neighbors: up=1, down=1, right=1, left maybe 0. So k=3 => 1 T. Good.
What about inverted T: (0,1), (1,0), (1,1), (1,2). Central cell is (1,1): neighbors: up (0,1), left (1,0), right (1,2). So k=3. Good.
Right-facing T: (0,1), (1,1), (2,1), (1,2). Central cell is (1,1): neighbors: up (0,1), down (2,1), right (1,2). So k=3. Good.
Now, what about a T shape that is not aligned with the orthogonal directions? Could the T be rotated 45 degrees? Typically, "T-shape" in grid problems means axis-aligned shapes (since we consider orthogonal adjacency). The problem says "2D grid of integers", but does not specify that the T must be axis-aligned. However, typically grid patterns are axis-aligned. The T-tetromino is axis-aligned. So it's safe.
But what if the T shape is defined as any four cells that are connected and form a T pattern but not necessarily with a central cell of degree 3? Could there be a T pattern where the stem is attached to the end of the crossbar? That would be an L shape, not T. So no.
Thus, our simple count: sum_{cells} C(# of orthogonal neighbors that are 1, 3) seems to capture all T-shapes.
But wait: Is there any possibility of double counting? Suppose we have two T's that share the same central cell? That cannot happen because the central cell's neighbors define the T. If a cell has, say, 5 neighbors? That's impossible in orthogonal grid: max 4. So the central cell can contribute at most 4 T's (when it has all 4 neighbors). And each T is uniquely identified by its central cell and which three arms. But could the same set of four cells be counted from two different central cells? Consider a shape where two cells each have three neighbors within the set? That would require a different topology. For a set of four cells that form a T, only one cell has degree 3. So no double count.
But what about overlapping T's that are distinct sets? They may share some cells, but each has its own central cell. So they are counted separately.
Thus, the total count = sum over all cells: if grid[i][j]==1, then compute k = count of adjacent cells (up, down, left, right) that are 1. Then add binomial(k,3). Binomial(k,3) is 0 for k<3, 1 for k=3, 4 for k=4.
But is it possible to have k>4? No, only up to 4. So we can just compute: if k==3 => 1; if k==4 => 4; else 0.
Thus, the algorithm is O(n*m) time and O(1) extra space (if we modify grid? we don't need to). We just need to iterate and count neighbors.
But wait: what about the case where the three arms themselves are not exactly as in a T because they might not be in a straight line? Actually, if the central cell has three neighbors in three directions, they automatically form a T? The arms are in those directions. The shape is then the central cell plus those three adjacent cells. That is exactly a T-tetromino because two of the directions are opposite (forming the crossbar) and the third is perpendicular (the stem). So yes.
But consider: what if the central cell has neighbors up, left, down? That gives an inverted T? Actually, up, left, down: that includes up and down (opposites) and left. That is a T pointing left? Let's map: The central cell (i,j). Neighbors: up (i-1,j), down (i+1,j), left (i,j-1). That shape: vertical line (up and down) and a left arm. That is a T pointing left? Actually, that's a left-facing T? The stem is to the left? In left-facing T, the crossbar is vertical? Typically, left-facing T: the crossbar is vertical? Let's draw:
*
But that's not matching. Actually, if we have up, down, left, then the shape looks like: central cell with arms up, down, left. That forms a T with the stem pointing left? The "crossbar" would be the vertical line (up and down) plus the central cell? Actually, the vertical line would be three cells: up, center, down. That's the crossbar? But the crossbar is usually three in a line; here we have three vertical? That would be a vertical line of three cells: up, center, down. And then an extra cell to the left attached to the center. That is indeed a T shape, but oriented so that the crossbar is vertical and the stem points left. That is one of the four orientations. So yes.
Thus, any set of three orthogonal directions yields a T.
Therefore, the solution is: iterate over each cell, if it's 1, check its four orthogonal neighbors (if within bounds) and count how many are 1. Then add to answer: 1 if count==3, 4 if count==4.
But is that all? What about T shapes that are not centered on a cell that has three neighbors? Could there be a T where the central cell is not the one with three neighbors because the shape is like:
A
A A A
Here the central cell is the middle of the crossbar? That's the same as before. So it's fine.
But wait: what if the T shape is defined differently, for example, as a pattern of 1's that looks like the letter T when considering all 1's in the grid? That is, a T-shape might be a connected component of 1's that exactly forms a T? But then we would need to find connected components that have exactly four cells and form a T. That is a different problem: count connected components of size 4 that are T-tetrominoes. But our method counts all T patterns even if they are part of larger components. For example, a plus shape (5 cells) would yield four T's according to our method, but the connected component of 5 cells is not a T of size 4; it's a plus. So if the problem intends to count T-shaped connected components (i.e., each component is a T), then we would need to find connected components of 1's that have exactly 4 cells and that shape. However, the phrase "number of 'T-shapes' of 1s" is ambiguous. It could mean count the number of occurrences of the T pattern (subgrid) or count the number of connected components that are T-shaped. Usually, problems about shapes in grids ask for counting distinct shape occurrences in the grid, often as subgrid patterns. For example, "count the number of X shapes in a grid" means find all positions where an X pattern appears (like 5 cells in an X). That often counts overlapping ones. So I'd lean toward counting each pattern occurrence, not component.
But we should consider the possibility that they want distinct T-shaped connected components. If that is the case, we would need to do a flood fill to find connected components of 1's, and for each component, check if its shape is exactly a T-tetromino (4 cells and the degrees match). But then a plus shape would be a component of size 5, not counted. But if there is a T component plus some extra 1's attached, it's not a pure T. So we'd need to check the component's graph structure: exactly 4 cells, and the degree distribution: one cell degree 3, three cells degree 1. Also connectivity: it must be connected. That's straightforward.
Which interpretation is more likely? Since the problem says "find the number of 'T-shapes' of 1s", it might be ambiguous. But many coding problems like "count T shapes in a binary matrix" refer to counting occurrences of the pattern as a subgrid, not necessarily connected components. For example, a known problem: "Count T shapes in a matrix" often defines the T as a specific arrangement of 1's in a 3x3 grid: like the middle of the top row and the entire middle column? Actually, I've seen problems: "Given a binary matrix, count the number of T-shaped patterns of 1's" where T is defined as 1's in positions (i,j), (i,j+1), (i,j+2), (i+1,j+1) (upright T). That's one orientation. They might ask for that orientation only. But here it says "T-shapes" plural, so maybe all orientations.
I recall a problem: "Count number of T's in a 2D array" where T is defined as 3 horizontal and 1 vertical attached to the middle. And they might consider all four rotations. That seems plausible.
Given the open-endedness, I should produce a solution that counts each T pattern occurrence based on the central cell approach, which is efficient and covers all orientations. I'll explain that.
But let's double-check if there's any nuance: The grid contains integers, not necessarily binary. We only care about 1's. So we treat any cell with value 1 as part of the pattern.
Algorithm:
- Input: grid, a list of lists of integers, dimensions m x n.
- Initialize count = 0.
- For i from 0 to m-1:
For j from 0 to n-1:
If grid[i][j] == 1:
k = 0
For each direction (dx,dy) in [(-1,0), (1,0), (0,-1), (0,1)]:
ni = i+dx, nj = j+dy
If ni, nj within bounds and grid[ni][nj] == 1:
k += 1
if k >= 3:
# number of ways to choose 3 out of k neighbors
# Since k can be 3 or 4, we can do:
if k == 3:
count += 1
elif k == 4:
count += 4
# k cannot be >4
- Return count.
But is it possible that a T pattern exists where the central cell is not the one with three neighbors because the T is defined differently? For example, if we consider the T shape as a set of four cells that are connected and form a T, but perhaps there is an alternative orientation where the "center" is not the degree-3 node? No, in a T-tetromino, the degree-3 node is unique. So central cell approach is sound.
However, we must verify that for each T pattern we count exactly once. The central cell is unique, so we count exactly once per T. Good.
But what about T patterns that are not entirely of 1's? We require all four cells to be 1. Our method only checks that the central cell is 1 and its neighbors are 1. That's sufficient because if the central cell and three specific neighbors are 1, then that set of four cells is all 1. However, what about the case where the central cell has 4 neighbors that are 1, but we count 4 T's (by leaving out one arm). For each omitted arm, we are effectively considering a T pattern that includes the central cell and the three other arms. But are we sure that those three arms are all 1? Yes, because all four neighbors are 1. So each combination yields a T. But note: In that plus shape, are those T patterns valid? The set of four cells: central + three arms. That set of cells is indeed all 1 and forms a T. So they should be counted. So our count of 4 is correct.
But what about the possibility of T patterns where the central cell has only 3 neighbors, but one of those neighbors is also adjacent to another 1 that could cause an alternative central cell? That doesn't matter.
Thus, the solution is straightforward.
But before finalizing, I want to consider if there is any alternative definition that might change things. Could the T-shape be defined as the shape formed by the '1's themselves, not requiring a central cell? Maybe they want to count the number of connected components that are exactly T-shaped. That would be a different algorithm: first, find connected components (using BFS/DFS). For each component, check if it has exactly 4 cells and if the graph degrees match that of a T (one node degree 3, three nodes degree 1). Also check connectivity: a tree with 4 nodes and degrees (3,1,1,1) is a T (specifically, it's a star with 3 leaves, which is the T shape). However, note that the T-tetromino is not just any tree with degree sequence (3,1,1,1); that degree sequence forces a central node connected to three leaves, which is exactly the T shape (since leaves are only connected to the center). That is the same as our pattern. But if the component has 4 cells but arranged differently (like an L shape: degrees (2,2,1,1) or a straight line: degrees (2,2,1,1) or a square: degrees (2,2,2,2)? Actually, a 2x2 block: each cell has 2 neighbors? In a 2x2 block, each cell has 2 within component? Possibly degrees: corner cells have 2 neighbors (if connected to the other two in the block). Actually, a 2x2 block: cells: (0,0),(0,1),(1,0),(1,1). Each cell has two adjacent cells within the block: e.g., (0,0) connected to (0,1) and (1,0). So degree 2 each. So not T. So checking degree distribution might be enough to identify T components. But careful: what if the component has 4 cells but is connected in a way that one node has degree 3 and others degree 1? That is exactly a star with 3 leaves. That's the T shape. But is it possible to have such a component that is not a T pattern? The only possible graph with 4 nodes and a node of degree 3 is a star. That's a tree with one internal node and three leaves. So that's the T shape. But is it possible that the geometric positions of the cells are not axis-aligned? If the graph is defined on orthogonal adjacency only (4-directional), then the degree-3 node must have three orthogonal neighbors. That means the three leaves are placed in three different directions from the center. That is exactly the T shape we described. So that matches.
Thus, if the problem meant connected components that are T-shaped (i.e., exactly 4 cells forming a T), then we could do: find all connected components of 1's (using BFS/DFS). For each component, if size==4, check if there exists a cell with degree 3 (within component). That would identify T components. But note: a component of size 4 that is T-shaped will have exactly one cell with degree 3 and three with degree 1. So we can compute degrees within the component. That's O(size). Total O(mn).
But which interpretation is more likely? The problem statement: "You are given a 2D grid of integers. Write a function to find the number of 'T-shapes' of 1s." It doesn't say "connected components" or "subgrids". Usually, "shapes" might refer to patterns that appear in the grid, not necessarily connected components. For example, a common problem: "Count the number of squares formed by 1s in a binary matrix" counts all axis-aligned squares, not necessarily connected components. So it's pattern counting. Also, they said "of 1s", meaning shapes made of 1's. It could be either.
I think the central cell neighbor count approach is much simpler and likely what they expect because it's O(n) and straightforward. However, it's worth considering if there is a catch: what if a T shape exists but the central cell is not 1? That can't happen because the central cell must be part of the shape, so it must be 1. So fine.
But there is a subtlety: In the T shape, the central cell must be the one with three neighbors within the T. But if the central cell has exactly three neighbors that are 1, but those neighbors are not arranged in the correct T configuration because they might not be pairwise opposite? As we argued, any three orthogonal directions include a pair of opposites, so it's automatically a T. But is it possible to have three neighbors that are all in directions that are not forming a T? In orthogonal directions, the only options are up/down/left/right. Any three will always include a pair of opposites. So that's fine. However, what about the geometry: if we have up, left, right, that's a T with crossbar left-right and stem up? Actually, that's an inverted T? Wait: up, left, right: central cell has up, left, right. That is a T with stem up? Let's draw: central cell (i,j). Up (i-1,j), left (i,j-1), right (i,j+1). That shape: a horizontal line of three cells? Actually, left, center, right are horizontal. And up is above the center. That's an inverted T? Actually, that's an upside-down T: the crossbar is horizontal (left-center-right) and the stem goes up. That's a valid T (inverted). So yes.
Thus, any three works.
But what if the three neighbors are not all distinct? They are distinct directions, so they are different cells. So fine.
Thus, the neighbor count method works.
Now, what about the case where the central cell has exactly three neighbors, but one of those neighbors is not part of the intended T because it might be connected to something else? That doesn't matter; the T pattern is just those four cells. So it's fine.
Thus, I'll adopt that.
But is there any T pattern that does not have a central cell with three orthogonal neighbors? Could a T shape be disconnected? No, a T shape is connected. So it must have a node with at least degree 2? Actually, any connected shape of 4 cells that is a tree must have at least two leaves. But the only tree with 4 nodes that has a node of degree 3 is the star. That's the T. So indeed the central cell must have degree 3. So our approach covers all T patterns.
Now, what about the plus shape? It has a central cell with degree 4. That yields 4 T's. That seems correct if we count all subpatterns. But if the problem expects to count only maximal T's or only isolated T's, then plus shape should not count as any T because it's not a T but a plus. That is a key ambiguity. Which is more likely?
Consider typical problems: "Count the number of 'T' shapes in a binary matrix" – I've seen such problems in coding challenges. Often they define a T as a specific pattern of 1's, like:
1 1 1
1
That's one orientation. And they ask for the number of such patterns. Overlapping is allowed. For example, if there is a plus shape, they might count two T's? Actually, in a plus shape, you have two T's? Let's check: The plus shape is:
1
111
1
That's a cross. That contains the upright T: the top row? Actually, upright T would be the top three cells and the middle of the bottom? That would be: positions: (0,0)?, let's index:
Assume grid:
Row0: col1=1
Row1: col0=1, col1=1, col2=1
Row2: col1=1
So the plus has a central cell at (1,1) with all four neighbors. Upright T pattern: three horizontal cells (row1, cols0,1,2) and one below center? Actually, the upright T shape defined earlier is: three horizontal on top and one below center. That would be: (0,1), (1,0), (1,1), (1,2)? That's inverted? Let's assign coordinates: upright T: crossbar at top, stem down: positions: (i,j-1), (i,j), (i,j+1), (i+1,j). So the crossbar is at row i, stem at row i+1. In the plus shape, if we take i=0? Then (0,0)? Not present. Actually, plus shape has row0 col1 =1, row1 col0=1, row1 col1=1, row1 col2=1, row2 col1=1. So we could have an upright T with crossbar at row1 (col0,1,2) and stem at row2 col1? That's (1,0),(1,1),(1,2),(2,1). That's a T shape: crossbar horizontal at row1, stem down from center (1,1) to (2,1). That's one T. Also inverted T: crossbar at row1 (col0,1,2) and stem up at (0,1): (0,1),(1,0),(1,1),(1,2). That's another T. Also left-facing T: crossbar vertical? That would be: (0,1),(1,1),(2,1) vertical and stem to the right at (1,2)? That gives (0,1),(1,1),(2,1),(1,2). That's a T? Check: central cell (1,1) with up, down, right: that's a right-facing? Actually, that's a T pointing right? Wait, left-facing T would have vertical crossbar and stem to the left. For left-facing, we need up, down, left. That would be (0,1),(1,1),(2,1),(1,0). That's also present in plus. And right-facing: up, down, right: (0,1),(1,1),(2,1),(1,2) - we already have that. So actually, plus shape yields 4 T's: upright, inverted, left-facing, right-facing. But note: upright and inverted use the horizontal crossbar, left/right use vertical crossbar. So plus yields exactly 4 T's. So our count of 4 from central cell degree 4 matches. So plus shape contributes 4. That seems plausible if we want to count all T subpatterns.
Now, if the problem intended to count only T-shaped components (i.e., connected components that are exactly T's), then a plus shape would not count at all because it's a component of size 5, not 4. So the answer would be 0 for a plus. Which interpretation is more common? I'm not sure. Let's think about the phrasing: "number of 'T-shapes' of 1s". It doesn't say "connected components". It says "shapes", which could be subconfigurations. In many grid pattern counting problems, they say "count the number of occurrences of a given shape" (like L-shapes, T-shapes, etc.) and they allow overlapping. For example, "count the number of plus signs" might count each plus shape. But here they say T-shapes. Given that they didn't specify the orientation or give a picture, but we can infer from common knowledge that a T-shape is a tetromino. In tetris, T-tetromino is well-known. So I think it's counting occurrences of that pattern.
Also, the neighbor count approach is very efficient and simple, which is typical for interview questions. The component approach would require DFS/BFS, which is also fine but slightly more code. But the neighbor count approach is O(1) per cell, overall O(mn). That's optimal. The component approach would be O(mn) as well, but with extra memory for visited flags.
Which one is more likely? I recall a problem: "Count the number of T's in a binary matrix where T is defined as 1's in the shape of the letter T". The typical solution is to check each cell as the center of the T. Actually, I think I've seen solutions that check for each cell if it and its three neighbors form a T. But they might check all four orientations explicitly.
Let's search memory: There's a known problem: "Count T shapes in a matrix" on GeeksforGeeks? I'm not sure. But I can reason: The central cell method is neat. However, there is a potential pitfall: what about T shapes that are not centered on a cell with three neighbors because the stem is attached to an end of the crossbar? That would be like:
A
A A A
But that's the same as before: the crossbar is three cells, the stem attached to the middle. That's our T. There is no T where the stem is attached to one end because that would be an L shape. So our method catches all.
Thus, I'll go with the neighbor count.
But wait: Is the central cell always the intersection point? Yes. However, what if the T is rotated 45 degrees? We only consider orthogonal adjacency. The problem didn't specify connectivity method. Usually, in grid patterns, adjacency is orthogonal (4-directional) unless specified "8-directional". So we assume 4-directional.
Thus, algorithm: For each cell that is 1, count its orthogonal neighbors that are 1. Let c = that count. Then the number of T's with that cell as center is C(c,3). Sum.
But is it possible that a T pattern could be counted with a different central cell? No, because the central cell is the only one with degree 3. So each T counted exactly once.
But what about a scenario where two T's share the same central cell? That would be two distinct T patterns with the same central cell but different sets of three arms. That can only happen if the central cell has all 4 neighbors, then we have 4 T's. That's fine. So we add 4.
Now, consider a shape that is like a "T" but with extra arms? That plus shape gave 4 T's. That's acceptable.
Thus, this algorithm seems correct.
But let's test with some small examples:
Example 1: grid = [[1,1,1],[0,1,0]] -> that's an upright T? Actually, upright T pattern: row0: 1,1,1; row1: 0,1,0. That's a T shape. Central cell at (0,1)? But (0,1) has neighbors: left (0,0)=1, right (0,2)=1, down (1,1)=1, up out of bounds => 3. So count=1 from that cell. Also check (1,1): it has up (0,1)=1, down out, left (1,0)=0, right (1,2)=0 => count=1? Actually, (1,1) has only one neighbor (up) so 0. Others: (0,0) has right (0,1)=1, down (1,0)=0 => 1 neighbor => 0. (0,2) similarly. So total count=1. Good.
Example 2: plus shape:
grid = [
[0,1,0],
[1,1,1],
[0,1,0]
]
Central cell (1,1) has 4 neighbors => count +=4. Others: (0,1) has down (1,1)=1, others 0 => count=0. (1,0) right=1 =>0, etc. So total=4. That seems right if we want to count all T's. But if the problem expects only isolated T's, they'd say 0? Probably not.
Example 3: a straight line of 4 cells: (0,0),(0,1),(0,2),(0,3). That's a line of four. Does it contain any T? No, because no cell has three orthogonal neighbors within the set? Check each cell: (0,1) has left and right (if they are 1). But also up/down none. So each internal cell has two neighbors, ends have one. So no cell with three neighbors => count 0. Good.
Example 4: a 2x2 block of 1's: each cell has two neighbors => no T.
Example 5: a T plus an extra arm? Suppose we have a central cell with three arms and also an extra cell attached to one of the arms? That might create a T with an extra cell not part of the T pattern, but we still count the T pattern that uses the central cell and three arms. The extra cell doesn't affect the count. So we would still count that T. That seems okay.
Thus, the algorithm seems robust.
Now, let's think about performance: O(m*n) time, O(1) extra space. That's efficient.
Now, we need to write a function. The function signature likely: def count_T_shapes(grid: List[List[int]]) -> int.
We'll implement that.
But we must be careful: the grid might be empty. Also, we should check boundaries.
Implementation:
def count_T_shapes(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
count = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
neighbors = 0
# up
if i > 0 and grid[i-1][j] == 1:
neighbors += 1
# down
if i < m-1 and grid[i+1][j] == 1:
neighbors += 1
# left
if j > 0 and grid[i][j-1] == 1:
neighbors += 1
# right
if j < n-1 and grid[i][j+1] == 1:
neighbors += 1
if neighbors >= 3:
# compute binomial coefficient: C(neighbors, 3)
# neighbors can be 3 or 4.
if neighbors == 3:
count += 1
else: # neighbors == 4
count += 4
return count
But wait, what about the case where neighbors=5? Impossible.
But there is a nuance: Are we counting T shapes that might be counted from a cell that is not the actual center because we are checking all cells? But as argued, only cells with degree 3 or 4 in the pattern will count. However, could there be a T pattern where the central cell has degree 3 but we count it multiple times from different central cells? No, because only that central cell has degree 3. But what about a T pattern that is part of a larger shape where the central cell has degree more than 3? That would be plus shape, and we count 4 T's from that central cell. But are those T patterns distinct? Yes, because each T omits a different arm. But are we sure that each of those T patterns corresponds to a unique set of four cells? Yes: central cell plus three specific arms. Since the arms are all 1, each set is valid.
But could a T pattern also be counted from another cell that is not the central but maybe from one of the arms? For an arm cell, its neighbor count might be 1 (only the center) or maybe more if attached to something else. But if it's just a simple T, the arm has only one neighbor (the center). So it won't contribute. So each T counted exactly once.
Thus, this method is correct.
But wait: consider a T shape that is part of a larger component where one of the arms is also connected to another 1 that is not part of the T, but that might increase the degree of that arm cell? For example, imagine a T where the stem cell at bottom is also connected to another cell to the right. That arm cell then would have two neighbors: the center and the extra cell. But that does not affect the central cell's neighbor count: central cell still has three neighbors (the three arms). So the T pattern that includes those four cells is still present. But would that T be counted? Yes, because central cell still has at least three neighbors that are 1. But note: the central cell might have four neighbors if the extra cell is also adjacent to the central? In that example, the extra cell is attached to the stem, not to the center. So central still has three. So we count one T. That's fine.
Now, what about a scenario where the central cell has four neighbors, but one of them is not part of the intended T because we want to count only the T patterns that are exactly those four cells? But if central cell has four neighbors, there are four possible T's, each omitting one arm. But if one of the arms is not actually part of a T because it might be isolated? But it's still a 1, so the set of four cells (center + the other three arms) is all 1, so it forms a T. So we count it.
Thus, the algorithm is simple and likely correct.
But we must also consider if the T shape might be defined differently: for example, some problems define a T as having the stem in the middle of the crossbar, but the crossbar is exactly three cells. That's exactly what we have. So it's fine.
I'll produce an explanation and the code.
But I should also note that if the grid contains values other than 0 and 1, we only care about 1.
Thus, final answer: Implement as above.
However, to be thorough, I should consider if there is any shape that our method counts as T but is not a T because the three arms are not in the correct configuration? As argued, any three orthogonal directions include a pair of opposites, so the arms form a crossbar of two opposite directions and the third is the stem. That is exactly a T. So it's always a T. So no false positives.
What about a shape like: central cell with neighbors up, down, left. That's a T with vertical crossbar (up and down) and left stem. That's fine.
Thus, the algorithm works.
Now, let's produce the solution.
But maybe the problem expects to count distinct T-shaped connected components? That would be a different approach. To decide, I could think about typical interview questions. The neighbor count approach is so trivial that it might be too trivial? But sometimes easy questions are asked. The problem statement says "Write a function to find the number of 'T-shapes' of 1s". It doesn't give more constraints. It might be a warm-up. The neighbor count is indeed straightforward.
I'll check the possibility: If they wanted components, they'd likely say "connected components that form a T shape" or "each T shape consists of exactly four connected 1's". But they didn't mention connectivity. So I'll stick with pattern counting.
To be safe, I could mention both interpretations in explanation, but the solution will implement the pattern counting approach. Alternatively, I could implement both and let the user choose? But the problem says "Write a function", so one function.
I'll produce a function that counts using the neighbor method.
Now, complexity: O(mn) time, O(1) space.
Edge Cases:
- Grid empty -> return 0.
- Grid with no 1's -> 0.
- Grid with one cell -> 0.
- Grid with two cells adjacent -> 0.
- Grid with three cells in L shape -> maybe 0? Actually, three cells in L: central cell might have two neighbors, so not 3. So 0.
- Grid with T shape: 1.
- Grid with cross: 4.
- Grid with two overlapping T's: e.g., two T's sharing some cells? That's okay, each central cell will have degree 3 or 4 accordingly.
But wait: what about a shape that has two T's that share the same central cell? That requires central cell degree >=4? Actually, if we have two distinct T patterns with the same central cell, that means the central cell has at least 4 neighbors? Because each T uses three arms. If we have two T's that are different, they must omit different arms. If we have two T's that both include the same three arms? That would be the same T. So different T's from same center correspond to different subsets of arms. To have at least two distinct subsets of size 3, we need at least 4 arms. So central cell must have at least 4 neighbors. That's possible if there is a plus shape (4 arms). That yields exactly 4 T's. If there were more than 4 neighbors? Impossible. So that's fine.
What about two T's that have different central cells? That's fine, they will be counted separately.
Thus, the method captures all.
Now, I'll write the explanation accordingly.
But I should also consider if the T shape could be counted from the central cell even if the arms are not exactly at the positions we think? For example, what if the grid has a T shape but the central cell is not the one with three neighbors because the shape is rotated differently? No, as argued.
Thus, I'm confident.
Now, produce final answer: function and explanation.
I'll include code in Python.
Let's write it clearly:
def count_T_shapes(grid):
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
count = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
# Count orthogonal neighbors that are 1
neighbors = 0
if i > 0 and grid[i-1][j] == 1:
neighbors += 1
if i < rows-1 and grid[i+1][j] == 1:
neighbors += 1
if j > 0 and grid[i][j-1] == 1:
neighbors += 1
if j < cols-1 and grid[i][j+1] == 1:
neighbors += 1
# If there are at least 3 neighbors, we can form T-shapes
if neighbors == 3:
count += 1
elif neighbors == 4:
count += 4
return count
Alternatively, we could use a dictionary or factorial, but not needed.
Now, explanation: We observe that a T-shape consists of a central cell with three adjacent cells in orthogonal directions (forming the three arms). The central cell is the only cell in the T that has degree 3 (i.e., three neighboring cells within the T). Conversely, any cell that has at least three orthogonal neighbors that are 1 can serve as the center of one or more T-shapes. Specifically, if it has exactly 3 such neighbors, it forms exactly one T; if it has 4 neighbors, it forms 4 distinct T's (each obtained by leaving out one of the four arms). Therefore, we can simply iterate over each cell, count its orthogonal 1-neighbors, and add the appropriate number of T's.
Complexity: O(mn) time, O(1) space.
I think that's it.
But to be thorough, I might also discuss that this counts all occurrences of the T-tetromino pattern, including overlapping ones.
Now, produce final answer.
We need to count the number of "T-shapes" formed by cells with value 1 in a 2D grid. A T-shape is the tetromino pattern consisting of four cells: three in a line (the crossbar) and one attached to the middle of that line (the stem). The shape can appear in any of the four orthogonal rotations.
Key Insight
- In any T-shape, there is exactly one cell (the center) that is adjacent to the other three cells.
- That center cell has degree 3 within the shape (three orthogonal neighbors that are part of the T).
- Conversely, any grid cell that is
1 and has at least three orthogonal neighbors that are 1 can serve as the center of one or more T-shapes:
- If it has exactly three such neighbors, it forms one T-shape.
- If it has four such neighbors (a plus shape), it forms four distinct T-shapes (each obtained by omitting one of the four arms).
Therefore, we can count all T-shapes by scanning every cell, counting its orthogonal 1‑neighbors, and adding 1 for exactly 3 neighbors or 4 for exactly 4 neighbors.
Algorithm
- If the grid is empty, return
0.
- For each cell
(i, j):
- If
grid[i][j] == 1, count how many of its four orthogonal neighbors (up, down, left, right) are also 1 and within bounds.
- Let
k be that count.
- If
k == 3, increment the answer by 1.
- If
k == 4, increment the answer by 4.
- Return the total.
Complexity Analysis
- Time: We visit each cell once and check up to 4 neighbors →
O(m·n) where m and n are grid dimensions.
- Space: Only a few integer variables →
O(1).
Reference Implementation (Python)
def count_T_shapes(grid):
"""
Count all occurrences of T-shapes (tetromino pattern) formed by 1's in a 2D grid.
Args:
grid: List[List[int]] – a 2D list of integers (0 or 1)
Returns:
int – total number of T-shapes
"""
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
total = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
# Count orthogonal neighbors that are 1
neighbors = 0
if i > 0 and grid[i-1][j] == 1: # up
neighbors += 1
if i < rows-1 and grid[i+1][j] == 1: # down
neighbors += 1
if j > 0 and grid[i][j-1] == 1: # left
neighbors += 1
if j < cols-1 and grid[i][j+1] == 1: # right
neighbors += 1
if neighbors == 3:
total += 1
elif neighbors == 4:
total += 4
return total
Explanation of Correctness
- Every T-shape contributes exactly one to the sum because its unique center cell has exactly three
1‑neighbors (the three arms). That cell will be visited and add 1.
- Every cell with three
1‑neighbors creates exactly one T-shape: the set consisting of the cell itself and its three 1‑neighbors is a valid T pattern (the three directions always contain a pair of opposites, ensuring the correct shape).
- Every cell with four
1‑neighbors creates exactly four T-shapes: choosing any three of the four arms yields a distinct T pattern (the omitted arm becomes the missing stem). The central cell adds 4 to the total, accounting for all subsets of size three.
- No overcounting: A given T pattern has a unique center cell (the one with degree 3), so it is counted exactly once when that cell is processed. Cells that are not centers (arms) have fewer than three neighbors and contribute nothing.
Thus, the algorithm counts all and only the T-shapes present in the grid.