AP® Computer Science A · Unit 4 · Topic 4.13

Finding a Value and Its Neighbors in a Grid

Finding a value in a grid means checking every row's elements one at a time until you find a match, then recording its row and column to look at the cells directly above, below, left, and right of it.

A 2D array is really an array of arrays, so there is no shortcut that lets you jump straight to a value. You sweep it the same way you'd read a page: row by row, and within each row, column by column. A nested loop handles this naturally, the outer loop walking down the rows and the inner loop walking across each row's columns. Once you find the target, you can break out of both loops immediately since there is no reason to keep checking cells you already know don't matter.

Once you have the row r and column c of a found cell, its orthogonal neighbors sit at four fixed offsets: one row up [r-1][c], one row down [r+1][c], one column left [r][c-1], and one column right [r][c+1]. These are the cells sharing an edge with it, not the diagonal ones. This is just arithmetic on the indices, no second search needed.

The complication shows up at the edges. A cell in row 0 has no row above it, and a cell in the last column has no column to its right, so blindly computing r-1 or c+1 can produce an index that doesn't exist in the array. Every neighbor-finding algorithm needs an if-check confirming the candidate row and column both fall between 0 and the array's last valid index before touching that cell. This bounds-checking habit carries straight into the next topics on traversing grids and recursive searches, where the same off-the-edge mistake is the usual bug.

Key terms

orthogonal neighbor
A cell sharing a full edge with another cell: directly above, below, left, or right, not diagonal.
nested loop
A loop inside another loop, used here so the outer loop picks a row and the inner loop scans its columns.
bounds check
A conditional test confirming an index falls within the valid range before using it to access an array.
row-major traversal
Scanning a 2D array one full row at a time before moving to the next row.

Watch it explained

  1. How it worksHow does a nested loop stop early once the target cell has been found?
  2. Worked exampleTrace finding the value 7 in { {3,7}, {1,9} } and report its row and column.
  3. Worked exampleFind the four orthogonal neighbors of cell [1][1] in a 3 by 3 grid.
  4. Going furtherWhat changes at an edge cell where some of the neighbors are off the grid?

Check yourself

Your turn1 of 2
Cell [15][14], away from any edge, has four orthogonal neighbors: [15-1][14], [15+1][14], [15][14-1], and [15][14+1]. Adding up the ROW index of all four neighboring cells, what is the total?

End of topic.