Start learning free

LESSON 259 OF 289 · NESTED LOOPS OVER GRIDS

Count in a Grid in C#: Matching Cells in an int[][]

Practice Read the full explanation

Given a grid of integers grid and an integer target, return how many cells of the grid are equal to target.

A grid is an array of rows, and each row is an array of integers.

 

Example 1:

Input: grid = [
  [1, 2, 3],
  [4, 2, 6],
  [2, 8, 2]
], target = 2
Output: 4
Explanation: 2 appears once in the first row, once in the second row and twice in the third row: 1 + 1 + 2 = 4.

Example 2:

Input: grid = [
  [-1, 5],
  [5, -1]
], target = -1
Output: 2
Explanation: The two cells with -1 are in different rows, and each one counts.

Example 3:

Input: grid = [
  [7, 8, 9]
], target = 4
Output: 0
Explanation: No cell is equal to 4.

 

Constraints:

  • grid has at least 1 row and 1 column, and every row has the same number of values.
  • Every value and target is an integer between -1000 and 1000; they can be negative.
STEP 1 OF 5
    Ctrl + Enter to check

    C# · NESTED LOOPS OVER GRIDS

    Count In Grid in C#, explained

    Problem overview

    CountInGrid receives a grid, an int[][] (an array of rows, each row an array of integers), and an int target. It returns how many cells of the grid are equal to target.

    In the grid with rows [1, 2, 3], [4, 2, 6] and [2, 8, 2], the target 2 appears once in the first row, once in the second and twice in the third: 1 + 1 + 2 = 4. In the grid [-1, 5], [5, -1] with target -1, the answer is 2: the two cells are in different rows, and each one counts. In the one-row grid [7, 8, 9] with target 4, nothing matches and the answer is 0.

    Approach: visit every cell once

    Nothing about the problem lets you skip a cell. A matching value can be anywhere, in any row, so the method has to look at all of them. The standard way to visit every cell of a jagged array is a loop over the rows with a loop over the values of each row inside it. Together they reach each cell exactly once.

    For each cell, the only question is whether it equals target. A counter that starts at 0 grows by 1 for every yes. The order of the visits doesn't matter, because adding 1 gives the same total in any order.

    Step by step

    1. Create int count = 0. No cell has been checked, so no match has been found.
    2. Loop over the rows with foreach (int[] row in grid). An int[][] is an array of rows, so each item is an int[]. The outer loop takes one row at a time, from the top.
    3. Inside it, loop over that row's values with foreach (int value in row). The inner loop goes through a whole row before the outer loop moves on, so every cell is visited once.
    4. Compare with ==: if value == target, do count++. Cells with any other value are skipped.
    5. Return count after both loops, so every cell is checked first.

    The solution in C#

    class Solution {
        public int CountInGrid(int[][] grid, int target) {
            int count = 0;
            foreach (int[] row in grid) {
                foreach (int value in row) {
                    if (value == target) {
                        count++;
                    }
                }
            }
            return count;
        }
    }
    

    C# details:

    • One equals sign or two. = assigns and == compares. Writing if (value = target) doesn't compile in C#, because an int can't be used as a condition. That is a safety net other languages lack.
    • count++. This adds 1 to count, the same as count += 1.
    • Jagged versus rectangular. The lesson's grid type is int[][], an array of arrays, so the loops are foreach over rows and then values. A rectangular int[,] is a different type: a foreach over it visits every cell directly, without rows.
    • No index is needed. The answer is a count of matches, so the position of a match is not used here. The next lesson, finding a cell, does need it.

    Edge cases and common mistakes

    • Returning inside a loop. A return count; inside the loops would end the method after the first cell.
    • Counting rows instead of cells. A row such as [2, 8, 2] contains the target twice. Counting once per row would give 3 for the first example, not 4. The inner loop counts each cell separately.
    • Negative targets. == compares negative numbers like any others. The target -1 on the second example returns 2.
    • No match. The counter never changes, and the method returns 0.
    • Forgetting the braces. Without { }, an if controls only the next statement. Keeping the braces makes it clear that count++ is what runs on a match.

    Testing

    gridtargetResult
    [[1, 2, 3], [4, 2, 6], [2, 8, 2]]24
    [[-1, 5], [5, -1]]-12
    [[7, 8, 9]]40
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free