This is not an answer about your algorithm but a couple of performance comments that wouldn't fit in the ongoing comment discussion.
I'm guessing that your deeply nested loops are taking up the bulk of the processing time, so optimizing them should help.
- Have you tried using jagged arrays instead of multidimensional arrays? Jagged arrays are faster for storage and retrieval.
I see that you have calculations like
(z * NumPieces)
in your inner-most loops. You can calculate that just after thefor (int z = 0...
loop and cache the value. You can possibly skip the multiplication entirely by incrementing a counter like this, but you might not see as much of a performance improvement:for (int z = 0, zNumPieces; z < PieceSize && currentCount < NumPieces; z++, zNumPieces += NumPieces)
You can do the same for your
(y * PieceSize)
calculation.- Your
place(...)
method is called in your inner-most loop, so any optimization there should help. Use afor
loop instead of aforeach
loop. They're faster. Also inplace()
, remove all of your calculations and instead pass in their results as parameters. This array accessboxContainer[piece.Z + z, piece.Y + y, piece.X + x]
is 6 loops deep but the additions can be calculated at the second, third, and fourth loops respectively. I don't know if the compiler optimizes this for you.- Your
print()
method is in there too (though I suspect not called that often), so optimize it. Instead of Console.Writing several small strings, piece them together in a StringBuilder and output that at the end of yourprint()
method. Better yet, keep all of your strings in memory and print them out at the very end of your program.
Again, I'm not commenting on your algorithm, just pointing out some issues. Your loops nest so deeply that you really should focus on making the deepest loops as efficient as possible.