I have a 2-dimensional integer array (say 1000 by 1000), let's call it matrix. Each cell in this matrix has a X- and Y-coordinate (each from 0 to 999 in this example). Initially all grid cells have a value of 0. During program runtime, some of the matrix cells are set to another value <> 0.
Now I need a fast function (algorithm) that takes some X and Y values and returns the value of the matrix at that coordinates. However, if the matrix at the specified X/Y location is 0, then the algorithm should determine a non-zero value within the matrix that is as close to the original X/Y location as possible.
I have thought about looping around the original X/Y position with increasing offset at each loop cycle, but I am not sure whether this is really the fastest algorithm...
Any ideas? I would prefer Java code, but any pseudo-code is also fine :)
Thanks in advance for your help! Kind regards, Matthias
An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. int x = a[1,1]; Console.
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
In Java, a table may be implemented as a 2D array. Each cell of the array is a variable that can hold a value and works like any variable. As with one dimensional arrays, every cell in a 2D array is of the same type. The type can be a primitive type or an object reference type.
A two-dimensional array is a data structure that contains a collection of cells laid out in a two-dimensional grid, similar to a table with rows and columns although the values are still stored linearly in memory.
If the array is relatively sparse and the number of tests is high relative to the number of inserts, the naive approach could take a long time.
The alternative is to build a spatial-partition tree such as a quadtree or k-d tree. Nearest-neighbor search is O(ln N) at the cost of O(ln N) insert times.
If you don't have any assumptions on how the matrix looks like, you must use brute force method to look at all values near the [X, Y] position.
It is just a work with for cycles, indices and proper ifs :-) There is no faster algorithm, because you don't have any information, guideline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With