Start learning free

LESSON 252 OF 281 · NESTED LOOPS OVER GRIDS

Grid Sum in C++: Nested Loops over a Vector of Vectors

Practice Read the full explanation

Given a grid of integers grid, return the sum of all the numbers in it.

A grid is a table of numbers made of rows. Every row has the same number of values, one in each column. Rows are counted from the top and columns from the left, both starting at 0.

 

Example 1:

Input: grid = [[1, 2, 3],
               [4, 5, 6]]
Output: 21
Explanation: The first row adds up to 1 + 2 + 3 = 6 and the second to 4 + 5 + 6 = 15. Together: 6 + 15 = 21.

Example 2:

Input: grid = [[-3, 4],
               [5, -6]]
Output: 0
Explanation: -3 + 4 + 5 + (-6) = 0. Negative numbers make the sum smaller.

Example 3:

Input: grid = [[7]]
Output: 7
Explanation: A grid with one row and one column holds a single number.

 

Constraints:

  • grid has at least 1 row and at most 10 rows.
  • Every row has the same number of values, at least 1 and at most 10.
  • Every value is an integer between -1000 and 1000.
STEP 1 OF 5
    Ctrl + Enter to check

    C++ · NESTED LOOPS OVER GRIDS

    Grid Sum in C++, explained

    Problem overview

    The function gridSum receives grid, a vector<vector<int>>, and returns the sum of every number in it. A grid is a table: the outer vector holds the rows, and each row is a vector with one value per column. Rows and columns are counted from 0.

    For [[1, 2, 3], [4, 5, 6]] the first row adds up to 6, the second to 15, and the answer is 21. For [[-3, 4], [5, -6]] the answer is 0, because negative numbers lower the total. A grid with a single cell, [[7]], gives 7.

    Approach: one loop for rows, one loop for values

    A single loop visits a flat list. A grid has two levels, so it takes two loops, one inside the other. The outer loop picks a row. The inner loop walks through that row's values. Together they reach each cell exactly once, and each value is added to a running total that starts at 0.

    The order of work is: for the first row, add all of its values; then the second row; and so on. The inner loop finishes completely before the outer loop moves on.

    Step by step

    1. Create total as an int set to 0. No number has been added yet.
    2. Loop over the rows. A range-based for over grid gives, in each turn, one element of the outer vector. That element is a vector<int>, so the loop variable is declared as vector<int> row.
    3. Loop over the values of the row. Inside the outer loop, a second range-based for goes over row with an int named value.
    4. Add the value. total += value runs once per cell. Negative values are added like any other.
    5. Return total after both loops. Returning inside a loop would add only part of the grid.

    The solution in C++

    class Solution {
    public:
        int gridSum(vector<vector<int>> &grid) {
            int total = 0;
            for (vector<int> row : grid) {
                for (int value : row) {
                    total += value;
                }
            }
            return total;
        }
    };
    

    C++ details:

    • Range-based loops copy by default. In for (vector<int> row : grid), row is a copy of each row. The copy is harmless here, because the function only reads the values. With grid = [[1, 2, 3], [4, 5, 6]], setting row[0] = 100 inside such a loop leaves grid[0][0] at 1, while the same assignment through vector<int>& row changes it to 100.
    • Avoiding the copies. For bigger grids, const vector<int>& row reads each row without copying it, and gives the same sum, 21, for the first example. The lesson's grids are at most 10 by 10, so the copies cost nothing noticeable.
    • The grid is passed by reference. The & in the parameter means the whole grid isn't copied when the function is called.
    • Nothing about the shape is assumed. The loops ask each row for its own length, so they work for any number of rows and columns.

    Complexity

    With R rows and C columns, the function adds R * C numbers, so the time is O(R * C), linear in the number of cells. The extra space is O(C) because of the row copy in this version, or O(1) with a reference. The lesson's limits are 10 rows, 10 columns and values between -1000 and 1000, so the total stays far below the limit of an int.

    Edge cases and common mistakes

    • Single cell. [[7]] runs each loop once and returns 7.
    • Negative values. [[-3, 4], [5, -6]] returns 0.
    • Resetting the total inside the outer loop. Declaring total = 0 inside the row loop would throw away the earlier rows. This lesson needs one total for the whole grid. A task that asks for one sum per row would need a fresh total for each row instead.
    • Returning too early. A return inside either loop leaves the function after the first value or row.
    • Wrong loop variable type. The outer loop variable must be a vector, not an int: each element of grid is a whole row.

    Testing

    • [[1, 2, 3], [4, 5, 6]] gives 21.
    • [[-3, 4], [5, -6]] gives 0.
    • [[7]] gives 7.
    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