Here's the algorithm for what you need to do:
- While there are shapes touching, figure out the rightmost shape (the one with the biggest right x-coordinate) that is touching another shape. Move it so its left edge is just right of the rightmost shape it was just touching.
- While there are shapes not next to something to the left of them, figure out the shape with the smallest left x-coordinate that is not next to something to the left of it. Move it so its left edge is just right of the shape with the largest right x-coordinate that lies in the y-range of the object.
Simple enough? Well, here's the simplified version:
- While there are shapes touching each other, move the rightmost one so it isn't touching any other shapes.
- While there are shapes not snuggled up to each other, move the leftmost one so it is snuggled up to the closest shape.
Edit: For example...
Suppose I took square 3 and plopped it on top of square 1 and square 2:
1111 44
1111 44
1133333
1133333
33333
3333322
3333322
2222
2222
Step 1. Find the rightmost shape that's intersecting something. In this case, that's shape 2. Move it right of what it's intersecting.
1111 44
1111 44
1133333
1133333
33333
333332222
333332222
2222
2222
Are there shapes touching now? Yes, and the rightmost one is shape 3. Move it right of the shape it's touching, shape 1:
1111 44
1111 44
111133333
111133333
33333
3333322
3333322
2222
2222
Are there shapes touching now? Yes, and the rightmost one is shape 2. Move it right of the shape it's touching, shape 3:
1111 44
1111 44
111133333
111133333
33333
333332222
333332222
2222
2222
Are there shapes touching now? No. So we're done step 1.
Step 2: Find the leftmost shape that's not snuggled up to anything. In this case, the leftmost one not snuggled up to anything is shape 4. Move it left so it's just right of the rightmost shape left of it that exists at the same y-coordinates as it:
111144
111144
111133333
111133333
33333
333332222
333332222
2222
2222
Anything not snuggled up to anything? Nope! So you're done!
As you can see, there's basically an expansion phase and a contraction phase. You do the expansion phase right to left so that nothing gets expanded right through something else. You do the contraction phase left to right so nothing gets contracted through something else.