Problem overview
The function centerOfGrid receives grid, a 3×3 grid of integers, and returns the number in its center: the one in the middle row and the middle column. The grid has exactly 3 rows, every row has exactly 3 numbers, and every number is between -1000 and 1000.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the middle row is [4, 5, 6] and its middle number is 5, so the answer is 5. For [[0, 0, 0], [0, 7, 0], [0, 0, 0]] it is 7. For [[9, 8, 7], [6, -5, 4], [3, 2, 1]] it is -5: the center can be any number, a negative one included.
Approach: index twice
A grid is a table made of rows, and Swift stores it as an array of arrays. The parameter type [[Int]] says it: grid is an array, and each of its items is itself an [Int]. That gives two levels of indexing:
grid[row]is a whole row, an[Int].grid[row][col]is the number in that row and column.
Both rows and columns are counted from 0. A grid with 3 rows has rows 0, 1 and 2, so the middle row is row 1. The same holds for the columns, so the center is at row 1, column 1.
Step by step
- Pick the middle row with
grid[1]. For the first example it is[4, 5, 6]. - Pick the middle column inside that row by adding a second index,
[1]. - Return the number
grid[1][1]. Its type isInt, which is what the function returns.
The solution in Swift
class Solution {
func centerOfGrid(_ grid: [[Int]]) -> Int {
return grid[1][1]
}
}
Details worth knowing:
- Row first, then column. In
grid[a][b],achooses the row andbthe column. For the first example,grid[1]is[4, 5, 6],grid[1][1]is 5,grid[0][2]is 3 (top row, right column) andgrid[2][0]is 7 (bottom row, left column). - Counting items.
grid.countis the number of rows, 3, andgrid[0].countis the number of columns in the first row, also 3. For a grid of unknown size, the middle row would begrid.count / 2, but this lesson fixes the size, so the plain index is enough. - Out of range crashes. Swift checks every array index at run time. Reading
grid[3][0]on a 3-row grid stops the program, instead of returning something random. - Value types. Arrays are values in Swift, so reading
grid[1][1]doesn't change the grid and doesn't copy it.
Edge cases and common mistakes
- Thinking the middle is 2. Counting starts at 0, not 1, so
grid[2][2]is the bottom-right corner (9 in the first example), not the center. - Swapping the indexes. For a symmetric position like the center,
grid[1][1]reads the same either way, but for other cells the order matters:grid[0][2]andgrid[2][0]are different cells. - Using one index.
grid[1]alone is a whole row,[4, 5, 6], not a number, and returning it doesn't match the return typeInt. - Negative numbers. The center -5 in the third example is returned as it is. No special case is needed.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives5.[[0, 0, 0], [0, 7, 0], [0, 0, 0]]gives7.[[9, 8, 7], [6, -5, 4], [3, 2, 1]]gives-5.
