A local maximum in a 2D array can be defined as a value such that all it\'s 4 neighbours are less than or equal to it, ie, for a[i][j]
to be a local maximum,
YOU DO NOT HAVE TO VISIT EVERY ELEMENT:
All you have to do is visualize the grid and you will see that this can be solved in much less than a flat n^2 (or I*J). Here are the optimizations, by level:
1] for an I*J matrix, you need only search (I-2)*(J-2). Why? the borders cannot be maxima because of the undefined elements:
e.g. grid[0][J] or grid[I][0] could never be maxima. because of the -1 neighbor.
So for a 10 by 12 grid, instead of visiting all 120 elements, we are looking at 80 elements.
2] if grid[I][J] is a maximum, then we can skip all cells adjacent to [I][J] as we continue the search. This will further reduce the number of elements to compare.
Hence, the answer is no, you don't have to visit every element.