Grid Algorithms: Search and Position
Part of: 2D Array
Searching a Grid A core 2D-array skill is searching for a value and reporting where it lives. Because you need the position, you must use indexed nested loops : the enhanced for loop cannot tell you r and c. The row-major search above finds the first occurrence (smallest row, then smallest column). The flag foundR == -1 stops the outer loop once a match is recorded. Tracking a Maximum and Its Location Finding the maximum value and its coordinates combines best-so-far tracking with index capture: - Initialize the best with the first cell grid[0][0], not 0, so negative grids work. - Update the value and both indices together whenever you find a larger cell. Position Output Conventions - Coordinates are usually reported as (row, column). - A row-major scan guarantees the first match found is the top-most, then left-most. Why Indices Matter Whenever a problem asks where , first match, location of the max, a specific cell's neighbors, you need indexed loops. Reading values alone is a job for for-each; locating them is a job for grid[r][c] with explicit r and c. This search-and-position pattern underlies many free-response grid questions.
Challenge: Find First Occurrence Position