When you consider placing of a new cube to partially built construct, not to consider several cases of rotations (depending on the position of face with non-zero number) - try to rotate randomly till the cube will fit already-constructed part. This is the most tedious part of the code (at least for me) that could be avoided.