The infection moves from a cell to the cells that share a side with it. So the first tool lists a cell's neighbors:
# up, down, left, rightSIDES = ((-1, 0), (1, 0), (0, -1), (0, 1))def neighbors(grid, r, c): found = [] for dr, dc in SIDES: nr, nc = r + dr, c + dc if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]): found.append((nr, nc)) return foundgrid = ["....", "....", "...."]for cell in [(0, 0), (0, 1), (1, 1), (2, 3)]: print(cell, neighbors(grid, *cell))
Predict
On an open 3 by 4 grid, how many neighbors does the corner (0, 0) have?
Pick one to see what it prints.
A grid question is a graph question that doesn't say so. The input is a list of strings of equal length. grid[r][c] is the cell in row r, counted from the top, and column c, counted from the left. There are len(grid) rows and len(grid[0]) columns, written R and C below.
Each cell is a node. Two cells are joined by an edge when they share a side: up, down, left or right. So a corner has 2 neighbors, a cell on an edge has 3, and an inner cell has 4.
Walls are cells you can't enter. Here they're #. The simplest way to handle them is to leave them out of the neighbor list, so a search never treats them as nodes.
Most examples below are forests on fire. It's the same spread as the infection, with other letters:
. is a tree.
# is a rock. It never burns.
F is a burning tree. Its fire spreads to the trees that share a side with it.
forest in the editor is one of them. Write size(grid), the number of rows and columns, and cells_of(grid, ch), every (r, c) that holds the character ch, such as each fire F.
Pick an answer above to see the rest
Instructions
1
Write size(grid): the pair (R, C), the number of rows, then the number of columns.
2
Write cells_of(grid, ch): every (r, c) where grid[r][c] == ch, row by row from the top, left to right in each row.