OK, first an example in two dimensions:
1 2 3
1 2 3 4
5 6 7 8
7 8 9 10
You start in the top left corner, obviously, and put the value into the result list. Next, you have to add all candidates that are reachable (through incrementing exactly one index) from there to some sort of sorted collection, here, that is the cells with the values 3 and 6. Then you take the lowest member out of that collection, put its value into the result list, add all candidates reachable from there that are not yet in the collection into that, and so on.
You will need:
- a data structure holding a candidate, with all indices and the result value (I represent that below as "
((i1 i2) value)
").
- a data structure for a collection of candidates, sorted by value. A heap seems ideal for that.
You will have to make sure that all candidates are unique by their indices when you put them into the collection. The values are not necessarily unique, but the heap should be sorted by them. Since a given set of indices always produce the same value, you will have to check for uniqueness of the indices only when you encounter that value while inserting into the heap. It might be an optimization to make the nodes of the heap not single candidates but a list of candidates with the same value.
Doing this with the above example: First, the result list is (2). The candidates are ((1 2) 3) and ((2 1) 6). Take the candidate with the lowest value out, put the value into the result list -> (2 3), find all new candidates' coordinates -> (2 2) and (1 3), calculate their values -> ((2 2) 7) and ((1 3) 4), put them into the candidates' heap (serialized representation here) -> ((1 3) 4) ((2 1) 6) ((2 2) 7), lather, rinse, repeat.
In tabular form:
result-list candidates
(2) ((1 2) 3) ((2 1) 6)
(2 3) ((1 3) 4) ((2 1) 6) ((2 2) 7)
(2 3 4) ((2 1) 6) ((2 2) 7) ((2 3) 8)
(2 3 4 6) ((2 2) 7) ((3 1) 8) ((2 3) 8)
(2 3 4 6 7) ((3 1) 8) ((2 3) 8) ((3 2) 9)
(2 3 4 6 7 8) ((2 3) 8) ((3 2) 9)
(2 3 4 6 7 8 8) ((3 2) 9) ((3 3) 10)
(2 3 4 6 7 8 8 9) ((3 3) 10)
(2 3 4 6 7 8 8 9 10)
I don't see a better way at the moment. The heap seems to need a number of nodes in the magnitude of the sum of n1, n2, and n3.