Dynamic line drawing only right angles

I’ve got a grid of boxes and I need to draw a line from one point to another when one of the boxes is selected. I can get this to work but the line draws through the other boxes. I need it to draw lines on certain paths where it doesn’t go over the boxes.

Here are some pics of what I’m trying to do.

I don’t really know how to even approach this. I’ve used the hitTest method for certain things, but how do I tell the line to go the way I want it once it “hits” one of the boxes?

Any suggestions on how to tackle this?