I have a grid represented with a flat vector, that is:
-------------
| 6 | 7 | 8 |
-------------
| 3 | 4 | 5 |
-------------
| 0 | 1 | 2 |
-------------
I access the elements with the indices from 0 to grid.size()-1
. I want to implement the Fast Sweeping Method. The main purpose of that method is that it does sweeps
, that is, grid traversals in specific directions. For the 2D case:
Sweep 1: Right-top
for [row = 0 : nrows-1]
for [col = 0 : ncols-1] --> Result: 0 1 2 3 4 5 6 7 8
Sweep 2: Left-top
for [row = 0 : nrows-1]
for [col = ncols-1 : 0] --> Result: 2 1 0 5 4 3 8 7 6
Sweep 3: Right-bottom
for [row = nrows-1 : 0]
for [col = 0 : ncols-1] --> Result: 6 7 8 3 4 5 0 1 2
Sweep 4: Left-bottom
for [row = nrows-1 : 0]
for [col = ncols-1 : 0] --> Result: 8 7 6 5 4 3 2 1 0
And then computing idx = row*ncols + col
.
This implementation is straightforward and its generalization to n
dimensions as well, when just nesting for
loops. However, I am working on a n-dimensional implementation and I am trying to generalize it in just 2 loops:
while (keepSweeping)
++sweep;
for (idx = init, idx == end, idx += inc)
// Traverse the grid
Computing init
, end
and inc
is being really challenging. Also inc
depends on ncols
and changes dynamically. For instance, for sweep 2 inc = -1
, but every ncols
times inc = -1 + 2*ncols
, so I achieve to go from 0 to 5.
Any help on how to do it? I am focusing firstly on the 2D case.
EDIT: I saw these threads http://www.cplusplus.com/forum/beginner/68434/ variable nested for loops that suggest to implement the loops recursively. Since I am looking for maximum performance, do you think that is a good idea?
Thank you!