← All lessonsUnit 1 · Swift for problems
Lesson 1.8

A grid

A grid is an array of rows, so the row comes first and the column second, and a position is used only once you know it is inside.

Reach for it when
The input is an array of arrays.
The move
grid[row][column]. The rows are grid.count and the columns are grid[0].count. A neighbour only counts if it is inside the grid.
Cost
Visiting every cell of a rows × columns grid is rows × columns steps.

The idea

Harper

I stopped a film for a whole cinema last night. All I did was look for my seat.

Arthur

Was the seat there?

Harper

That turned out to be the question. We'll come back to it. It's a small cinema: two rows, three seats in each. Your ticket says row 1, seat 2. What do you do first?

Arthur

Find the row. Then walk along it to the seat.

Harper

Why not the seat first?

Arthur

Seat 2 of what? Until I'm standing in a row, there is no seat 2.

Harper

And in Swift?

Arthur

grid[1][2]. A grid is an array of rows. grid[1] is the whole of row 1, which is an array itself, and [2] is the seat along it. Both count from zero, so that's the back row, last seat.

Harper

On a graph I say x first. Across, then up.

Arthur

A ticket isn't a graph. It says how far back, then how far along: row, then column. Read it across first and you sit in someone else's seat. If you're lucky.

Harper

How many rows are there?

Arthur

grid.count. It's an array of rows, so its count is the rows.

Harper

And seats in a row?

Arthur

grid[0].count, the length of the front row. Every row is the same length, so one row is enough to ask.

Harper

And in a cinema with no rows? How long is the front row then?

Arthur

There's no front row to ask. Swift doesn't answer zero. It stops the program.

Harper

My seat's in the corner. How many neighbours have I got?

Arthur

Two. One in front of you and one beside you. The other two would be sitting in the wall.

Harper

So before I lean over to a neighbour?

Arthur

You ask whether there's a seat there. Is the row at least 0, and less than the number of rows? Is the column at least 0, and less than the number of columns? Four questions, every time.

Harper

I asked none of them last night.

Arthur

I had gathered.

That is the whole tool. A grid is an array of rows, a cell is grid[row][column] with the row first, and a position is used only after you know it is inside.

Here is the cinema from above, with the screen at the top and a number in every seat. The one in brackets is Harper's: grid[1][2], which holds 7.

       column 0  column 1  column 2
row 0      3         8         1
row 1      6         2        [7]

The shape

This is what you know by heart: a walk past every seat.

Swift
/// Every number in `grid`, row by row. `grid` has at least one row.
func rowByRow(_ grid: [[Int]]) -> [Int] {
    let rows = grid.count                    // how many rows
    let columns = grid[0].count              // how many columns: the length of row 0
    var cells: [Int] = []
    for row in 0..<rows {                    // the row loop is outside
        for column in 0..<columns {          // the column loop is inside
            cells.append(grid[row][column])  // one cell: the row first
        }
    }
    return cells
}

It has three parts, and each is there for a reason.

This job only reads, so the walk over the values from "Loops and indexes" would do it too: for seats in grid, then for number in seats. Both are right. Learn the one with the two indexes. A column, a write and a neighbour all have to know where they are, and the indexes are the where.

One more line is worth knowing by heart, and step 7 builds it: the test that says whether a position is inside the grid.

Watch it run

The cinema is [[3, 8, 1], [6, 2, 7]]. Here is every pass of the inner loop.

rowcolumngrid[row][column]cells after
003[3]
018[3, 8]
021[3, 8, 1]
106[3, 8, 1, 6]
112[3, 8, 1, 6, 2]
127[3, 8, 1, 6, 2, 7]

There are 6 passes, one for each seat: 2 rows times 3 columns. Look at the fourth row. column has gone back to 0, and row has moved on by one. The inner loop finishes a whole row before the outer loop moves once. That is what "row by row" means.

Step by step

Step 1

Make a grid of zeros with Array(repeating:count:)

A grid job often starts with a cinema that nobody has sat in yet: a grid of the right size with 0 in every seat, ready to be written in.

Swift
/// A grid of `rows` rows and `columns` columns, with 0 in every cell.
func zeros(_ rows: Int, _ columns: Int) -> [[Int]] {
    return Array(repeating: Array(repeating: 0, count: columns), count: rows)
}

What is new: the thing that is repeated is itself an array. Read the line from the inside out. Array(repeating: 0, count: columns) is one row, with a zero for each column. The outer call repeats that row, once for each row. zeros(2, 3) gives [[0, 0, 0], [0, 0, 0]].

The inner count is the columns and the outer count is the rows. The other way round gives [[0, 0], [0, 0], [0, 0]]: three rows of two, which is a different cinema.

Step 2

Visit every cell, row by row

One cell first, then all of them.

Swift
/// The number at row `row`, column `column` of `grid`.
func numberAt(_ grid: [[Int]], _ row: Int, _ column: Int) -> Int {
    return grid[row][column]                 // the row first, then the column
}

What is new: two pairs of brackets, and the row goes in the first. For Harper's ticket, row 1 and column 2, it gives 7.

The walk does that for every cell. It is the shape itself, written from an empty function, and what is new in it is the two loops, with the row loop outside. For the cinema it gives [3, 8, 1, 6, 2, 7].

The same walk can write. Put grid[row][column] on the left of an =, and that one cell changes and no other: after grid[1][2] = 7, a grid of zeros is [[0, 0, 0], [0, 0, 7]].

Swift
/// A grid of `rows` rows and `columns` columns whose cells hold 1, 2, 3 and so on,
/// row by row.
func numbered(_ rows: Int, _ columns: Int) -> [[Int]] {
    var grid = Array(repeating: Array(repeating: 0, count: columns), count: rows)
    var number = 0
    for row in 0..<rows {
        for column in 0..<columns {
            number += 1
            grid[row][column] = number       // write one cell
        }
    }
    return grid
}

What is new: writing a cell. numbered(2, 3) gives [[1, 2, 3], [4, 5, 6]]: the numbers run along the front row before the back row starts, because the walk does.

The shape counts on at least one row. A grid with no rows has no grid[0], and asking for it stops the program. When nothing promises a row, ask first.

Swift
if grid.isEmpty {                        // ask first: is there a row at all?
    return []
}
let rows = grid.count
let columns = grid[0].count              // safe now: there is a row 0

What is new: a question before grid[0]. With it, a grid with no rows gives []. One of this step's problems is the walk without the question, for you to mend.

Step 3

One row as an array, and one column as an array

A row is already there. The grid is an array of rows, so one pair of brackets hands you a whole row.

Swift
/// Row `row` of `grid`.
func oneRow(_ grid: [[Int]], _ row: Int) -> [Int] {
    return grid[row]
}

What is new: grid[row] is an array. For row 1 of the cinema it gives [6, 2, 7].

A column is not there in the same way: no array holds the last seat of every row. So you build it, by taking the same seat from each row.

Swift
/// Column `column` of `grid`, from the top row to the bottom.
func oneColumn(_ grid: [[Int]], _ column: Int) -> [Int] {
    let rows = grid.count
    var cells: [Int] = []
    for row in 0..<rows {
        cells.append(grid[row][column])      // the same column of every row
    }
    return cells
}

What is new: one loop, over the rows, with the column held still. For column 2 it gives [1, 7]. And grid[2] is not column 2: one pair of brackets always means a row.

Step 4

The sum of each row, and of each column

Swift
/// The sum of each row of `grid`.
func rowSums(_ grid: [[Int]]) -> [Int] {
    let rows = grid.count
    let columns = grid[0].count
    var sums: [Int] = []
    for row in 0..<rows {
        var sum = 0                          // starts again for every row
        for column in 0..<columns {
            sum += grid[row][column]
        }
        sums.append(sum)                     // this row is finished
    }
    return sums
}

What is new: where sum is made. It is made inside the row loop, so it starts again from 0 for every row, and it is kept when its row is finished. For the cinema this gives [12, 15].

Make sum once, above both loops, and it never starts again. The answer becomes [12, 27]: the second number has the front row in it as well. One of this step's problems is that mistake, for you to mend.

For the columns, the two loops change places.

Swift
/// The sum of each column of `grid`.
func columnSums(_ grid: [[Int]]) -> [Int] {
    let rows = grid.count
    let columns = grid[0].count
    var sums: [Int] = []
    for column in 0..<columns {              // the loops have changed places
        var sum = 0
        for row in 0..<rows {
            sum += grid[row][column]         // the brackets have not
        }
        sums.append(sum)
    }
    return sums
}

What is new: the column loop is outside, so the walk goes down a whole column before it moves along. The brackets do not change places: it is still grid[row][column], row first, whichever loop is outside. This gives [9, 10, 8].

Step 5

The largest row sum

This is LeetCode 1672, Richest Customer Wealth. Each row is one customer, and each number in it is the money in one of that customer's bank accounts. The answer is the most that any one customer has: the sum of each row, and then the largest of the sums.

Swift
/// LeetCode 1672. The largest sum of any one row of `accounts`.
func maximumWealth(_ accounts: [[Int]]) -> Int {
    let rows = accounts.count
    let columns = accounts[0].count
    var sums: [Int] = []
    for row in 0..<rows {
        var sum = 0
        for column in 0..<columns {
            sum += accounts[row][column]
        }
        sums.append(sum)
    }
    return sums.max() ?? 0
}

What is new: only the last line. The largest of the sums is the answer, and max() from "Sorting by a key" finds it. max() hands back an optional, because an empty array has no largest, and ?? 0 says what to give then. The problem promises at least one customer, so it never comes to that.

For the cinema the answer is 15. The largest single number, 8, is in the front row, and the back row still adds up to more. The lesson "Best so far" finds a largest with a loop of your own.

Step 6

Turn the rows into columns

This is LeetCode 867, Transpose Matrix. The first row of the grid becomes the first column of a new grid, the second row becomes the second column, and so on. So the number at row 1, column 2 moves to row 2, column 1.

Swift
/// LeetCode 867. `matrix` with its rows turned into columns.
func transpose(_ matrix: [[Int]]) -> [[Int]] {
    let rows = matrix.count
    let columns = matrix[0].count
    var turned = Array(repeating: Array(repeating: 0, count: rows), count: columns)
    for row in 0..<rows {
        for column in 0..<columns {
            turned[column][row] = matrix[row][column]
        }
    }
    return turned
}

What is new: the row and the column change places, in two spots. The new grid is made with the two counts the other way round, because two rows of three turn into three rows of two. And each number is written at [column][row]. Everything else is old: the grid of zeros from step 1, and the walk and the write from step 2.

For the cinema this gives [[3, 6], [8, 2], [1, 7]]:

       column 0  column 1
row 0      3         6
row 1      8         2
row 2      1         7

The front row, 3, 8, 1, now reads down the first column.

Make the new grid the old shape, and a square grid never shows the mistake. Any other grid stops the program at the first write past an edge.

Step 7

Is a position inside the grid?

Swift
/// Whether row `row`, column `column` is a cell of `grid`.
func isInside(_ grid: [[Int]], _ row: Int, _ column: Int) -> Bool {
    let rows = grid.count
    let columns = grid[0].count
    return row >= 0 && row < rows && column >= 0 && column < columns
}

What is new: four questions joined with &&, so all four must be true. The row is at least 0, and less than rows. The column is at least 0, and less than columns.

For the cinema, row 1, column 2 gives true. Row 2, column 1 gives false: the two rows are numbered 0 and 1, so row 2 is one past the back row. Row -1 gives false too: nothing is in front of the front row.

It is < and not <=, because the number of rows is never itself a row. With <= the test says true for row 2. One of this step's problems is that slip, for you to mend.

The test never reads the cell, and that is the point of it. grid[2][1] does not hand back a wrong number. It stops the program. So ask first, and read only when the answer is true.

Step 8

The neighbours above, below, left and right that are inside the grid

From any seat there are four moves: up a row, down a row, left a seat, right a seat. Each is a change to the row and a change to the column.

Swift
/// The cells above, below, left and right of a cell that are inside `grid`,
/// in that order. Each is `[row, column]`.
func neighbours(_ grid: [[Int]], _ row: Int, _ column: Int) -> [[Int]] {
    let rows = grid.count
    let columns = grid[0].count
    let moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]       // up, down, left, right
    var inside: [[Int]] = []
    for (rowChange, columnChange) in moves {
        let nextRow = row + rowChange
        let nextColumn = column + columnChange
        if nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns {
            inside.append([nextRow, nextColumn])
        }
    }
    return inside
}

What is new: the four moves, kept in an array and tried one at a time. Each lands on a position, and the four questions from step 7 decide whether it is kept.

Here are the four moves from Harper's corner seat, row 1, column 2.

movechangelands oninside?
up(-1, 0)[0, 2]yes
down(1, 0)[2, 2]no
left(0, -1)[1, 1]yes
right(0, 1)[1, 3]no

So her neighbours are [[0, 2], [1, 1]]: two, as Arthur said. In a cinema of three rows of three, the middle seat has 4 neighbours, a seat on an edge has 3 and a corner seat has 2. Only a seat with no wall beside it has all four.

What goes wrong

Most of these end the same way: the program stops with "Index out of range". When you see that, a row or a column has gone outside the grid.

Column first. grid[column][row] is the ticket read as x and y. In a walk over a grid that is not square it stops the program, and that is the lucky case: you find out at once. On a square grid it runs, and reads another seat: in [[1, 2], [3, 4]], grid[0][1] is 2 and grid[1][0] is 3. Say "row, column" as you type the brackets.

Each count in the other's place. A row is measured against rows, and a column against columns. Write row < columns and column < rows, and every square grid still agrees. The cinema does not: that test says false for Harper's own seat, and true for row 2, column 1.

grid[0] when there are no rows. grid[0].count stops the program for a grid with no rows: there is no front row to ask. Unless the problem promises a row, ask grid.isEmpty first, and the walk gives [].

The two counts of a new grid the wrong way round. In Array(repeating:count:) the inner count is the columns and the outer count is the rows. The other way round gives [[0, 0], [0, 0], [0, 0]] where [[0, 0, 0], [0, 0, 0]] was wanted.

A sum that never starts again. var sum = 0 belongs inside the outer loop. Above it, the cinema's row sums come out as [12, 27] where they should be [12, 15].

<= at the far edge. Rows are numbered from 0 to rows - 1, so the number of rows is never itself a row. row <= rows says true for row 2 of the cinema, and the read that follows stops the program.

Counting on four neighbours. A corner seat has 2 and an edge seat has 3. Reading a neighbour you never asked about stops the program at the wall.

Say it back

1

Your ticket says row 1, seat 2. How do you write that seat, and which number comes first?

Show the answerHide the answer

grid[1][2]. The row comes first, because grid[1] is the whole row and [2] picks the seat from it. It is the other way round from x and y.

2

How many rows and columns does a grid have, and what happens when it has no rows?

Show the answerHide the answer

grid.count rows and grid[0].count columns. With no rows there is no grid[0], and asking for it stops the program. Ask grid.isEmpty first, unless a row is promised.

3

In Array(repeating: Array(repeating: 0, count: columns), count: rows), which call makes one row?

Show the answerHide the answer

The inner one: a zero for each column. The outer call repeats that row, once for each row.

4

For the sum of each column, what changes places and what does not?

Show the answerHide the answer

The loops change places: the column loop goes outside. The brackets do not: it is still grid[row][column].

5

Which four questions say that a position is inside the grid, and when do you ask them?

Show the answerHide the answer

Is the row at least 0? Is it less than rows? Is the column at least 0? Is it less than columns? Ask all four before you read the cell.

6

How many neighbours does a cell have?

Show the answerHide the answer

Four at most. A cell on an edge has three and a corner has two: the rest are outside the grid.

7

How did Harper stop a film by looking for her seat?

Show the answerHide the answer

Her ticket said row 1, seat 2. She read it as x and y, across first, and went to row 2, seat 1. The cinema's two rows are numbered 0 and 1, so there is no row 2, and she never asked whether the position was inside. A position outside a grid does not give you a wrong seat. It stops the program, for everyone.

Practise

These are this lesson's problems in the Orithms app, in the order they come.

ProblemLevel
1A grid of zerosEasy
2The number at a positionEasy
3Every cell, row by rowEasy
4Number the cells, row by rowEasy
5A grid with no rowsEasy
6One row as an arrayEasy
7One column as an arrayEasy
8The sum of each rowEasy
9A sum that never starts againEasy
10The sum of each columnEasy
11The largest row sumEasy
12Turn the rows into columnsEasy
13Is it inside the grid?Easy
14One row too manyEasy
15The neighbours inside the gridEasy

These problems are done in the Orithms Mac app.

Every piece of code and every number in a lesson comes from a file that was compiled and run.