Get adjacent elements in a two-dimensional array?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Neighbor lookup in a two-dimensional array is a basic building block for grid algorithms. You need it for maze search, flood fill, game logic, image processing, and shortest-path problems. Most bugs come from boundary errors, inconsistent coordinate conventions, or using the wrong adjacency model.
Define Grid Coordinates and Bounds
Use one coordinate convention and keep it everywhere. In Python, the common model is (row, col).
A neighbor coordinate is valid only when both indices stay inside bounds.
Having one reusable bounds function reduces repeated mistakes.
Four-Direction Adjacency
Four-direction movement includes up, down, left, and right only.
Use this model for problems where diagonal motion is disallowed.
Eight-Direction Adjacency
Eight-direction movement adds diagonals.
Use this model for cellular automata or image kernels where diagonal influence is required.
Build a Reusable Neighbor Generator
Most grid algorithms need coordinates only. A generator avoids unnecessary list allocation in tight loops.
This helper can be reused in BFS, DFS, Dijkstra, and A-star implementations.
Example: BFS With Neighbor Helper
Here is a runnable shortest-path example on an unweighted grid with blocked cells.
A single tested neighbor helper keeps traversal logic clean.
Performance Notes
For large grids, neighbor lookup runs many times. Practical optimizations:
- Define direction arrays once, not inside inner loops.
- Yield coordinates instead of full tuples with copied values.
- Avoid converting between
(x, y)and(row, col)repeatedly.
These improvements matter in simulation and pathfinding workloads.
Common Pitfalls
- Accessing neighbors without bounds checks. Fix: centralize bounds logic and reuse it.
- Mixing coordinate order across functions. Fix: standardize on
(row, col)and document it. - Including the current cell as its own neighbor in 8-direction loops. Fix: skip the
dr == 0 and dc == 0case. - Using diagonal movement when problem rules allow only 4-direction movement. Fix: select adjacency model from problem statement first.
- Reallocating neighbor lists in hot loops. Fix: use generators or fixed direction arrays for better performance.
Summary
- Neighbor lookup is fundamental for most grid algorithms.
- Choose 4-direction or 8-direction adjacency based on domain rules.
- Use shared bounds checks and neighbor helpers to reduce bugs.
- Generators improve performance and keep traversal code cleaner.
- Consistent coordinate conventions are critical for correctness.

