How to make an enemy move along a wall?

I want to make a enemy that move along a wall in my 2d game. First thing i did was check if in front of it is a wall , if true then rotate 90 degrees up. 152884-picture2.png But what if before it isn’t a wall but under it like this:
152845-picture1.png

And i think rotate 90 degrees isn’t the best way because sometime my enemy don’t touch the wall.

It looks like your algorithm could be:

  • Always move to a free field that is surrounded by walls, but where I have not yet been
  • When moving to a free field, mark it as having been there (and rotate body towards wall if wanted)
  • When no option is left, clear all having-been-there markers and try again