Any pointers how to solve this puzzle in general (not using fixed size arrays and so on) ?