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. What usually goes wrong. What you see What caused it How to fix it --- --- --- The reported position is the last match instead of the first The scan kept running after a match was recorded Break out of the inner loop and stop the outer one once a match is stored The row and the column come out swapped The indices were printed or captured in the wrong order Report t

Challenge: Find First Occurrence Position