As searching for an unknown area, for an unknown object.
You can use something like Pledge's algorithm until you've found the boundaries of your space, record all information as you go. Then go have a look at all unseen squares using your favorite drift/pathfinding algorithm. If, at any point along the way, you see the flag, stop what you're doing and use your favorite pathfinding algorithm to go home.
A simple Breadth First Search/Depth First Search will work, but they are slow algorithms.
A* is the more elegant approach, especially if you know the location of the flag relative to yourself. The classic heuristic to use is the manning distance (number of moves assuming no obstacles) to the destination.
These approaches involve creating objects that represent squares on your map and creating "paths" or series of the square to hit (or steps to take).
These algorithms are useful for the return trip as the robot's mission is to capture the flag and bring it to his home base(which represents his starting position).