Problem overview
The method countInGrid receives grid, a list of rows where each row is a list of integers, and an integer target. It returns how many cells of the grid equal target.
For a grid with rows [1, 2, 3], [4, 2, 6] and [2, 8, 2] and target = 2, the value 2 appears once in the first row, once in the second and twice in the third: the answer is 4. For [[-1, 5], [5, -1]] with target = -1 the answer is 2, because the two matches are in different rows and each counts. For [[7, 8, 9]] with target = 4 nothing matches, so the answer is 0.
Approach
Counting matches is the counter pattern you know from flat lists, applied at two levels. Start a counter at 0, visit every cell, and add 1 whenever the cell equals the target. Visiting every cell of a grid takes a loop over the rows with a loop over each row's values inside it.
Unlike a search, this problem never stops early: a match does not end the work, because later cells may match too. The function has to look at every cell before it answers.
Step by step
- Create
count = 0. No cell has been checked, so no match is found yet. - Loop
rowovergrid. Eachrowis a list of integers. - Loop
valueoverrow. The inner loop covers a whole row before the outer loop moves down, so every cell is visited exactly once. - If
value == target, add 1 tocount. Any other value is skipped. - Return
countafter both loops, once every cell has been checked.
The solution in Python
class Solution:
def countInGrid(self, grid: List[List[int]], target: int) -> int:
count = 0
for row in grid:
for value in row:
if value == target:
count += 1
return count
Python details:
==compares,=assigns. Writingif value = target:is a syntax error in Python.- The
ifsits inside the inner loop. Its indentation decides that it runs once per cell. Placed at the outer loop's level, it would test only the last value of each row. - Negative targets work like any other integer:
-1 == -1is true.
Python's lists have a count method, so each row's matches are row.count(target). Adding those up, sum(r.count(target) for r in grid), gives the same result as the nested loops. The loops show the work that count does inside.
Edge cases and common mistakes
- Stopping at the first match. A
returninside theifwould answer 1 for the first example instead of 4. Count, then return after the loops. - Counting rows instead of cells. A row with the target twice, like the last row of the first example, adds 2, not 1.
- Returning inside a loop. The function would stop after the first row or the first cell.
- No match. The counter is never incremented and the function returns 0, with no special case.
- Zero as a target. It is an ordinary value; nothing treats it as "empty".
Testing
[[1, 2, 3], [4, 2, 6], [2, 8, 2]]with target2gives4.[[-1, 5], [5, -1]]with target-1gives2.[[7, 8, 9]]with target4gives0.
