You are in the right direction.
Model your problem as an undirected graph G=(V,E), where V = { all pens }, E = { (u,v) | there is a wall between u and v }withw((u,v)) = cost of wall between u and v
To “connect all the handles” - you are really looking for a subgraph: G'=(V,E')so that an auxiliary graph will be connected G'[there is a path between every two nodes], and the cost of the walls in E 'is minimal.
- . [ , , - - , ]
, MST, Prim Kruskal