This algorithm is not optimal for winning the game, but it is fairly optimal in terms of performance and amount of code needed:
if(can move neither right, up or down)
direction = left
else
{
do
{
direction = random from (right, down, up)
}
while(can not move in "direction")
}