Sign in

In-Bounds Grid Neighbors

core

Grid BFS/DFS starts by listing the in-bounds neighbors of a cell. Implement neighbors(r, c, n, m) for an n-row by m-column grid: return the up, down, left, and right neighbors of (r, c) that lie inside the grid, in that exact order.

A neighbor outside [0, n) in row or [0, m) in column is omitted entirely, not clamped: a corner cell may return as few as 0 pairs, an edge cell 2, and an interior cell all 4.

Example: neighbors(0, 0, 3, 3), the top-left corner of a 3x3 grid, has no valid up or left neighbor, so it returns just {(1,0), (0,1)} (down, then right).

Input format: each test in tests/*.in is laid out as:

  • Line 1: r c n m, the four arguments to neighbors(r, c, n, m): the cell's row and column, then the grid's row and column counts.

Test 05.in reads:

0 0 1 1

This is cell (0, 0) in a 1 x 1 grid: all four candidate neighbors fall outside, so the result is empty.

Where you'll use it:

✦ Solution & editorial unlock with the pass.

Loading...