I think it can be done using a simple algorithm that loops through the shapes.
For each shape
- "pretend to drag it to the left"
see if there is a match horizontally
Yes: Add UID's of matches to a temp array
see if there is a match vertically
Same yes/no logic
- "pretend to drag to the right"
- "pretend drag up.." & same
- "pretend drag down.." & same
Finally highlight the UUD's somehow
something like that. maybe there are more optimal way, but i'm all for easy solutions
Hope that helps