A matrix is an array of rows. One index chooses a row and another chooses a column, giving every cell an address such as grid[row][column].

Rows and columns make boundaries

A cell can have neighbors above, below, left, and right. Before visiting a neighbor, check that its row and column remain inside the grid.

  • The number of rows is len(grid).
  • The number of columns is len(grid[0]) for a rectangular grid.
  • Visiting every cell takes O(rows × columns) time.

Nested loops match the shape

Add every value in a gridPython
def grid_total(grid):
    total = 0

    for row in grid:
        for value in row:
            total += value

    return total

board = [[1, 2, 3], [4, 5, 6]]
print(grid_total(board))  # 21

Grids appear in images, maps, spreadsheets, games, and dynamic-programming tables. Draw a small grid and label coordinates when index logic becomes confusing.

Later, graph traversal will help us explore connected regions inside a grid.

Your tiny challenge

Draw a 3-by-4 grid. What are the coordinates of its corners? Which neighbors are valid for the top-left cell?