If I understand you correctly then you're looking for a path finding algorithm. It's not a particularly easy topic, but there have been some threads on this, here on PGD. I'm pretty sure you'll be able to find some source code. too ([Here] for example)