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
- Create
totalas anintset to 0. No number has been added yet. - Loop over the rows. A range-based
forovergridgives, in each turn, one element of the outer vector. That element is avector<int>, so the loop variable is declared asvector<int> row. - Loop over the values of the row. Inside the outer loop, a second range-based
forgoes overrowwith anintnamedvalue. - Add the value.
total += valueruns once per cell. Negative values are added like any other. - Return
totalafter 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),rowis a copy of each row. The copy is harmless here, because the function only reads the values. Withgrid = [[1, 2, 3], [4, 5, 6]], settingrow[0] = 100inside such a loop leavesgrid[0][0]at 1, while the same assignment throughvector<int>& rowchanges it to 100. - Avoiding the copies. For bigger grids,
const vector<int>& rowreads 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 = 0inside 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
returninside 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 ofgridis a whole row.
Testing
[[1, 2, 3], [4, 5, 6]]gives 21.[[-3, 4], [5, -6]]gives 0.[[7]]gives 7.
