Start learning free

LESSON 257 OF 671 · NESTED LOOPS OVER GRIDS

Count in a Grid in Java: Counting 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

    JAVA · NESTED LOOPS OVER GRIDS

    Count In Grid in Java, explained

    Problem overview

    Given a grid grid of type int[][] and an integer target, countInGrid returns 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. Values and the target can be negative.

    For the grid [[1, 2, 3], [4, 2, 6], [2, 8, 2]] and target = 2, the answer is 4: one 2 in the first row, one in the second and two in the third. For [[-1, 5], [5, -1]] and target = -1 it is 2, because the two cells are in different rows and each one counts. For [[7, 8, 9]] and target = 4 it is 0.

    Approach

    This is the usual counting pattern, with a grid instead of a flat array: keep a counter, visit every item once, and add 1 whenever the item matches. Visiting every cell of an int[][] takes two loops, since the grid holds rows and each row holds values. The outer loop picks a row, and the inner loop goes through that whole row before the next row begins. Every cell is checked exactly once, and the order doesn't matter, since we only count matches.

    Step by step

    1. Create an int named count starting at 0. No cell has been checked yet, so no match has been found.
    2. Write a for-each loop with an int[] named row over grid. Each item of an int[][] is a row, which is an int[].
    3. Inside it, write a for-each loop with an int named value over row.
    4. Inside the inner loop, if (value == target), add 1 to count with count++. Cells with any other value are skipped.
    5. After both loops, return count. Returning inside a loop would end the method before every cell was checked.

    Tracing the first example

    For the 3 by 3 grid and target = 2, the first row [1, 2, 3] has one 2, so count becomes 1. The second row [4, 2, 6] adds another, making 2. The third row [2, 8, 2] has two, bringing the count to 4. The method returns 4.

    The solution in Java

    class Solution {
        public int countInGrid(int[][] grid, int target) {
            int count = 0;
            for (int[] row : grid) {
                for (int value : row) {
                    if (value == target) {
                        count++;
                    }
                }
            }
            return count;
        }
    }
    

    Java details in this code:

    • == is right for int. value and target are primitive int values, so == compares the numbers. The rule that == on objects compares references applies to Integer or String, not to primitives. If the grid held Integer objects, you would use equals.
    • One equals sign or two. value == target tests, and value = target assigns. In an if, the assignment form doesn't compile for int, because the condition must be a boolean.
    • The outer loop variable is an array. int[] row refers to a row inside the grid, not a copy. This code only reads it.
    • No position needed. The task asks only for how many cells match, not where they are, so for-each loops are enough. The next kind of task, finding a position, needs row and column numbers.

    Edge cases and common mistakes

    • No match. If nothing equals target, count stays 0, which is the right answer. For [[7, 8, 9]] and target = 4, the method returns 0.
    • Several matches in one row. Every cell counts, including two equal cells next to each other. The inner loop adds to count for each one.
    • Negative targets. -1 is an ordinary int, and value == target works the same way. For [[-1, 5], [5, -1]] and target = -1, the result is 2.
    • Counting rows instead of cells. Adding 1 once per row that contains the target would give 3 for the first example instead of 4. Count in the inner loop.
    • Returning inside the loops. A return count; placed in a loop would stop after the first row or the first cell.

    Testing

    • countInGrid(new int[][]{{1, 2, 3}, {4, 2, 6}, {2, 8, 2}}, 2) returns 4.
    • countInGrid(new int[][]{{-1, 5}, {5, -1}}, -1) returns 2.
    • countInGrid(new int[][]{{7, 8, 9}}, 4) returns 0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free