I assume that what your doing is checking the player's position
relative to the ghost (for each ghost) and then moving towards it,
and then getting stuck against walls. You need to add some primitive AI,
so that if the ghost hits a wall, it goes in a different direction,
until it can go in the direction it wants.
# #
# ###
# G
### ###
#
### #
# #
G is the ghost, and it "wants" to go left, so it will head left and get
stuck against the wall
# #
# ###
#G
### ###
#
### #
# #
Then the AI kicks in. It chooses which direction to go in. This could
either be randomly, or, slightly more intelligent, depending again on
the position of the player, as they are not likely to be directly to
the left. However you choose, say it decides to go down:
# #
# ###
#
###G###
#
### #
# #
So it does. It still remembers that it wants to go left, but it can't,
so it goes down again:
# #
# ###
#
### ###
G#
### #
# #
Now it CAN go left, so it does, and continues on its way
# #
# ###
#
### ###
G #
### #
# #