Interesting problem!

I am not sure that your algorithm will work in all cases. For example, imagine a page of a size 3x3:
123
456
789with five images 12, 47, 36, 89 and 5 There is no horizontal...