Problem 258996 · easy · Phase 02 Linear Data Structures

Four-Neighbour Counts

2d-lists · neighbours · bounds-checking

Given a grid grid of 0s and 1s, return a new grid of the same shape where each cell holds the number of 1s among its four orthogonal neighbours (up, down, left, right). The cell's own value is not counted. Neighbours outside the grid do not exist.

Examples

Input:  grid = [[1, 0, 1],
                [0, 1, 0]]
Output: [[0, 3, 0],
         [2, 0, 2]]
Explanation: the middle cell of the top row touches 1s on its left, right and below.

Input:  grid = [[1]]
Output: [[0]]

Constraints

  • 1 <= rows, cols <= 100

Goals

  • Visit the up/down/left/right neighbours of a cell
  • Skip neighbours that fall outside the grid
Starting Python…