You might want to look into pathfinding solutions. There are already a number of answers on this site which discuss various pathfinding implementations, such as this one:
If you have more specific questions that are particular to your implementation, come back and ask!
answered Jan 08 '10 at 02:30 PM
A simple approach would be:
answered Jan 08 '10 at 04:24 PM