It all should be translatable to C++. I basically created a small (max 4 items) stack for each place in the grid. When I move to a new square, I push my previous position to new location's stack. That lets me unwind my path and detect loops. The code iterates backwards and puts a block on the spot.