Algorithm to find a shortest past under a special condition
Use a pathfinding algorithm, such as BFS, A*, or some other suitable algorithm.  Here each rectangle is treated as a vertex of the graph, and you imagine an edge from rectangle r1 to rectangle r2 if that's an allowed move (if you currently have rectangle r1, you can get to r2 in a single step).

Think of the rectangle as the "state" of the system at any point in time.  When you want to explore the statespace of a system, pathfinding algorithms are often worth a try.