Question: There is a square grid in which there are empty and filled blocks. A number of contiguous blocks form an object. My bot can find out the status of it's neighbouring 8 blocks (whether they are filled or not). It can move to a neighbouring position if there is no filled block over there.

I have 2 questions

First one : 

My code works for the case when there are no tight spaces (i.e., when objects have at least 2 empty blocks between them). But, in the case when there can be a single space between 2 blocks, since my bot has no way of knowing if the neighbouring filled blocks belong to the same or different objects, it fails to encircle the object.

Is there a way to get around this problem?

The other question : 

What would be the best search strategy for this? I've been thinking of assigning rewards to neighbouring spaces on the basis of how many unvisited spaces it will allow me to visit if I visit that neigbouring space, but a much simpler strategy seems to be :
keep going right till you hit the wall, the go up and keep going left, then up and right ....
Is there a catch to this approach?

Answer: 
An easy way to encircle an object is to just 'stick your left hand out' and walk forwards, keeping your hand on the object.

So, for your bot, you need to keep track of its direction, then if the tile to the left (relative to its current direction) is free then turn left and move forward.
If its not free, and ahead is free then move forwards, and if ahead isn't free then turn right.
Maybe just [use pathfinding. A\* is a good and easy algorithm for that](http://en.wikipedia.org/wiki/A%2a_search_algorithm).