Problem overview
The method centerOfGrid receives a 3×3 grid of integers, grid, and returns the number in its center: the one in the middle row and the middle column. The grid is a list of 3 rows, and every row is a list of 3 numbers. Rows and columns are counted from 0, so the middle row is row 1 and the middle column is column 1. Numbers range from -1000 to 1000.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the middle row is [4, 5, 6] and the result is 5. For [[0, 0, 0], [0, 7, 0], [0, 0, 0]] the result is 7. For [[9, 8, 7], [6, -5, 4], [3, 2, 1]] the result is -5: the center can be any number, including a negative one.
Approach
A grid in Python is a list that contains lists. Indexing it takes two steps. The first index picks a row, which is a whole list. The second index picks one number from that row. So grid[row][col] is the number at that row and column.
Because the grid is always 3×3 and counting starts at 0, the middle is at row 1 and column 1. No loop is needed, and the other eight numbers don't matter.
Reading a nested list is like reading a table: first find the row, then look along it for the column. Printing grid[1] for the first example shows [4, 5, 6], and printing grid[1][1] shows 5. If you are ever unsure where a cell is, print the row first and check it before indexing into it.
Step by step
- Pick the middle row.
grid[1]is the second list. For the first example it is[4, 5, 6]. - Pick the middle column inside that row. Index
1again:grid[1][1]. For[4, 5, 6]that is5. - Return it. The solution is the single expression
grid[1][1].
The solution in Python
class Solution:
def centerOfGrid(self, grid: List[List[int]]) -> int:
return grid[1][1]
Some details worth knowing:
- The annotation
List[List[int]]says "a list of lists of integers". It documents the shape of the input, and Python doesn't enforce it at run time. - Rows come first.
grid[1][0]is row 1, column 0: for the first example that is4, whilegrid[0][1]is2. Swapping the two indexes reads a different cell, although for the center, both are1. - Negative indexes work on each level too.
grid[-2][-2]reaches the same cell asgrid[1][1], since in a list of 3 the index-2is the same position as1. The plain1is easier to read. - For grids of any odd size, the middle index would be the length divided by 2 with
//. Here the size is fixed at 3, so1is enough.
Edge cases and common mistakes
- Counting from 1. The rows are 0, 1 and 2.
grid[2][2]is the bottom-right corner,9in the first example, not the center. - Using one index.
grid[1]is a whole row,[4, 5, 6]. The answer must be a single number, so you need the second index. - Going out of range.
grid[3]doesn't exist in a 3-row grid and raisesIndexError: list index out of range. - Negative numbers. The center
-5is returned as it is. Don't take its absolute value.
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.
