I think easiest way to solve this is to use very simple maze solver tactic. That is the "wall follower".
- Find wall
- Put your hand on the wall, either left or right of you
- Keep hand on wall
- Start moving
- Never let go off the wall, if there is a turn, you turn with the wall and if its "dead end" you turn but you still keep your same hand on the same side ( ie. left or right of you )
Eventually, you will find your way out.
So, how does this help you? You have to check after every wall placement, if you can walk around the wall ( either inside or outside, does not matter ) by walking near the wall until you get back to your starting point. However, it's easier to follow from inside so you can check the location of you newly place wall and go tile by tile towards the castle and find empty spot. That way you know you should be inside the walls.
- Place wall
- Find open spot near the wall
- Check where the wall is considering your position now ( up,left,down or right)
Then, for example if
- Wall is below you
- Move left
- If there is wall below you, goto 5
- if there is NO wall below you, there might be turn to down, so move down.
- There should be wall on the right side now, if not break out and fail
- Move down with the same logic.
Google for: wall follower algorithm or something like that, to find examples
Keep the hand on the wall.